Я работал над небольшим программным обеспечением для быстрого чтения, просто для удовольствия :), вдохновленный Spritz.
Может ли кто-нибудь выяснить, как остановить это от использования с помощью speedr_stop(); функционировать?
Здесь html:
<div class="speedr-wrapper">
<input class="speedr-button" type="button"value="click me" onclick="speedr_init(200)" />
<div class="speedr"></div>
</div>
<div class="readable">
<p>This paragraph should be read in the speedr div.</p>
... и javascript (использует jquery)
function speedr_init(speed) {
//toggle the button - currently can't get it to stop :(
$('.speedr-button').attr('onclick', "speedr_stop()");
$('.speedr-button').attr('value', "stop me");
var arr = $('.readable').text().trim().split(/[ ]+/);
var writeLoop = function(i) {
if (arr[i]) {
setTimeout(function() {
$('.speedr').append("<h4>" + arr[i] + "</h4>");
writeLoop(i + 1);
}, speed);
setTimeout(function() {
$('h4').remove();
}, speed-1);//speed for the timout to clear must be 1 less than the original speed
}
};
writeLoop(0);
}
function speedr_stop() {
clearTimeout(writeLoop); //this does not work - suggestions???
$('.speedr-button').attr('onclick', "speedr_init("+speed+")");
$('.speedr-button').attr('value', "start me");
}
Здесь ссылка codepen: http://codepen.io/dsm/pen/hHirb
Благодарю!
Вы должны уловить возвращаемое значение setTimeout
чтобы очистить таймер, то есть идентификатор таймера. Это число. Итак, ниже приведен модифицированный код с улавливанием идентификаторов таймера и текущим состоянием вашего приложения,
var timeouts = [];
var isRunning = false;
function speedr_init(speed) {
if(isRunning){
speedr_stop();
return;
}
isRunning = true;
//toggle the button - currently can't get it to stop :(
$('.speedr-button').attr('value', "stop me");
var arr = $('.readable').text().trim().split(/[ ]+/);
var writeLoop = function(i) {
if (arr[i]) {
timeouts.push(setTimeout(function() {
$('.speedr').append("<h4>" + arr[i] + "</h4>");
writeLoop(i + 1);
}, speed));
timeouts.push(setTimeout(function() {
$('h4').remove();
}, speed-1));//speed for the timout to clear must be 1 less than the original speed
}
};
writeLoop(0);
}
function speedr_stop() {
timeouts.splice(0,timeouts.length).forEach(clearTimeout);
isRunning = false;
$('.speedr-button').attr('value', "start me");
}
Еще одно сомнение, откуда приходит speed
и какова должна быть ценность? В вашем предыдущем коде оно будет неопределенным и также вызовет ошибки скрипта.
Надеюсь это поможет!
var writeLoop
вне обеих функций и измените вашу функцию speedr_init так, чтобы она не говорилаvar writeLoop = function...
, а простоwriteLoop = function...