Executing code after clearInterval


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.

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
}

First of all, you probably meant:

var timer = setInterval(loop, 30);

Secondly, are you sure calling clearInterval does not clean the queue of pending loop() calls? If this is the case, you can easily disable these calls by using some sort of guard:

var done = false;

function loop() {
    if(!done) {
      // print something to screen
    }
}

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

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