Skip to content Skip to sidebar Skip to footer

I Need Stop A Loop With Settimeout Inside In Javascript

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) {

Solution 1:

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.

Solution 2:

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

Solution 3:

Clean solution: http://jsfiddle.net/y4nEN/2/

interval = setInterval(function() {

    $("#div").append(tx[x] + " <br />");
    x++;

    if(x >= tx.length)
        clearInterval(interval);

}, 500);

Post a Comment for "I Need Stop A Loop With Settimeout Inside In Javascript"