问题
i have a loop with setTiemout inside and i need stop it via onClick button
var loop = function(){
for (var i = 0; i < tx.length; i++) {
setTimeout((function(x) {
return function() {
$("#div").append(tx[x] + " <br />");
};
})(i), 500 * i);
}
};
$("#start").on("click", loop);
$("#stop").on("click", stop);
i have the example in JSFiddle start|stop loop with buttons
Thank's
回答1:
How about this?
var tx = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "g", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "y", "z"];
var run = true;
var txIndex = 0;
var loop = function(){
if(run && txIndex < tx.length) {
$("#div").append(tx[txIndex] + " <br />");
txIndex++;
setTimeout(loop, 500 );
}
};
$("#start").on("click", function() { run=true; loop() } );
$("#stop").on("click", function() { run=false } );
Fiddle demo
回答2:
You'll have to retain pointers to the results of the setTimout()
method so you can later call clearTimout
on them.
If you need to break from the loop itself, you'll want to set a flag somewhere else in your code, then check the value inside of the for loop. If that flag is set, then break
.
回答3:
Clean solution: http://jsfiddle.net/y4nEN/2/
interval = setInterval(function() {
$("#div").append(tx[x] + " <br />");
x++;
if(x >= tx.length)
clearInterval(interval);
}, 500);
来源:https://stackoverflow.com/questions/25036857/i-need-stop-a-loop-with-settimeout-inside-in-javascript