我一直在研究一款只是为了好玩的小型读卡器应用程序,受到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
谢谢!
答案 0 :(得分:1)
您必须捕获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
来自哪里,价值应该是什么?在您之前的代码中,它将是未定义的并且也会抛出脚本错误。
希望这有帮助!