本文介绍了我需要在JavaScript中停止setTimeout的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个setTiemout内循环,我需要通过onClick按钮停止它$ b $ pre $ code var循环= function(){
for(var i = 0; i setTimeout((function(x){
return function(){
$(#div ).append(tx [x] +< br />);
};
})(i),500 * i);
}
};
$(#start)。on(click,loop);
$(#stop)。on(click,stop);
我有JSFiddle
解决方案
如何?
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);
}
}; (click,function(){run = true; loop()});
$(#start)。 (click,function(){run = false});
$(#stop)。
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 JSFiddlestart|stop loop with buttons
Thank's
解决方案
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 } );
这篇关于我需要在JavaScript中停止setTimeout的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!