我需要在JavaScript中停止setTimeout的循环 [英] I need stop a loop with setTimeout inside in JavaScript

查看:159
本文介绍了我需要在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 JSFiddle start|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 } );

Fiddle demo

这篇关于我需要在JavaScript中停止setTimeout的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆