How to use setInterval and clearInterval?

JavascriptJquery

Javascript Problem Overview


function doKeyDown(event) {
    switch (event.keyCode) {
    case 32:
        /* Space bar was pressed */
        if (x == 4) {
            setInterval(drawAll, 20);
        }
        else {
            setInterval(drawAll, 20);
            x += dx;
        }
        break;
    }
}

Hi all,

I want to call drawAll() once not creating a loop that call drawAll again and again, should I use recursive method for that or should I use clearInterval?

Also please tell me to use clearInterval? Thanks :)

Javascript Solutions


Solution 1 - Javascript

setInterval sets up a recurring timer. It returns a handle that you can pass into clearInterval to stop it from firing:

var handle = setInterval(drawAll, 20);

// When you want to cancel it:
clearInterval(handle);
handle = 0; // I just do this so I know I've cleared the interval

On browsers, the handle is guaranteed to be a number that isn't equal to 0; therefore, 0 makes a handy flag value for "no timer set". (Other platforms may return other values; NodeJS's timer functions return an object, for instance.)

To schedule a function to only fire once, use setTimeout instead. It won't keep firing. (It also returns a handle you can use to cancel it via clearTimeout before it fires that one time if appropriate.)

setTimeout(drawAll, 20);

Solution 2 - Javascript

clearInterval is one option:

var interval = setInterval(doStuff, 2000); // 2000 ms = start after 2sec 
function doStuff() {
  alert('this is a 2 second warning');
  clearInterval(interval);
}

Solution 3 - Javascript

Side note – if you want to use separate functions to set & clear interval, the interval variable have to be accessible for all of them, in 'relative global', or 'one level up' scope:

var interval = null;	

function startStuff(func, time) {
	interval = setInterval(func, time);
}

function stopStuff() {
	clearInterval(interval);
}

Solution 4 - Javascript

I used angular with electron,

In my case, setInterval returns a Nodejs Timer object. which when I called clearInterval(timerobject) it did not work.

I had to get the id first and call to clearInterval

clearInterval(timerobject._id)

I have struggled many hours with this. hope this helps.

Solution 5 - Javascript

Use setTimeout(drawAll, 20) instead. That only executes the function once.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajView Question on Stackoverflow
Solution 1 - JavascriptT.J. CrowderView Answer on Stackoverflow
Solution 2 - JavascriptJoshua - PendoView Answer on Stackoverflow
Solution 3 - JavascriptHynekSView Answer on Stackoverflow
Solution 4 - JavascriptPJ3View Answer on Stackoverflow
Solution 5 - JavascriptdlevView Answer on Stackoverflow