I need stop a loop with setTimeout inside in JavaScript

余生颓废 提交于 2019-12-11 14:52:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!