Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
249 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...