我一直在研究一个小型的速度读取器应用程序,只是出于娱乐目的:)受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
以清除计时器,即计时器ID。这是一个数字。因此,下面是修改后的代码,其中捕获了计时器ID和应用程序的运行状态,
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
来自哪里,价值是什么?在您之前的代码中,它将是未定义的,并且还会引发脚本错误。
希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句