Executing code after clearInterval

mshang picture mshang · Oct 1, 2011 · Viewed 8k times · Source

I have a setInterval calling a loop which displays an animation.

When I clearInterval in response to a user input, there are possibly one or more loop callbacks in queue. If I put a function call directly after the clearInterval statement, the function call finishes first (printing something to screen), then a queued loop callback executes, erasing what I wanted to print.

See the code below.

function loop() {
    // print something to screen
}

var timer = setInterval(loop(), 30);

canvas.onkeypress = function (event) {
    clearInterval(timer);
    // print something else to screen
}

What's the best way to handle this? Put a delay on the // print something else to screen? Doing the new printing within the loop?

Edit: Thanks for the answers. For future reference, my problem was that the event that triggered the extra printing was buried within the loop, so once this executed, control was handed back to the unfinished loop, which then overwrote it. Cheers.

Answer

pimvdb picture pimvdb · Oct 1, 2011

You could also use a flag so as to ignore any queued functions:

var should;

function loop() {
    if(!should) return; // ignore this loop iteration if said so

    // print something to screen
}

should = true;
var timer = setInterval(loop, 30); // I guess you meant 'loop' without '()'

canvas.onkeypress = function (event) {
    should = false; // announce that loop really should stop
    clearInterval(timer);
    // print something else to screen
}