Unknown5566
Unknown5566

Reputation: 1

SetInterval and clearInterval explanation

var fps = 30;
var drawInterval;

imageSprite.addEventListener('load',init,false);

function init() {
    drawBg();
    startDrawing();
}

function draw() {        
    clearJet();
    drawJet();
}

function startDrawing() {
    stopDrawing();
    drawInterval = setInterval(draw,1000 / fps);
}

function stopDrawing() {
    clearInterval(drawInterval);
}

Can anybody explain why do we execute the function stopDrawing() before drawInetrval and how will this code execute.

Upvotes: 0

Views: 131

Answers (2)

iConnor
iConnor

Reputation: 20209

It is simply clearing the interval so that you are not running multiple intervals at the same time.

Upvotes: 0

fusio
fusio

Reputation: 3675

Essentially with clearInternal you are stopping the interval referenced by drawInterval.

You could look at it as if it were setting drawInterval = null.

That is done to prevent multiple intervals firing: each time startDrawing is called, you reset the current ongoing interval and start a new one that will fire in 1000/fps milliseconds, i.e. drawInterval will fire 1000/fps milliseconds after startDrawing is called for the last time.

Upvotes: 1

Related Questions