0

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

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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

interval = setInterval(function() {

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

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

}, 500);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.