Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript setInterval Limits?

I have an application using JavaScript's setInterval() to run a digital clock. I was wondering if it has a timeout, or limit, to the amount of times it can execute this function.

like image 202
Ethan Turkeltaub Avatar asked Oct 20 '11 14:10

Ethan Turkeltaub


People also ask

How do you limit setInterval?

“set interval time limits js” Code Answer'svar intervalID = setInterval(alert, 1000); // Will alert every second. // clearInterval(intervalID); // Will clear the timer. setTimeout(alert, 1000); // Will alert once, after a second.

Is it good to use setInterval in JavaScript?

In the above program, the setInterval() method calls the greet() function every 1000 milliseconds(1 second). Hence the program displays the text Hello world once every 1 second. Note: The setInterval() method is useful when you want to repeat a block of code multiple times.

How many times does setInterval run?

When your code calls the function repeatEverySecond it will run setInterval . setInterval will run the function sendMessage every second (1000 ms).

Is setInterval infinite?

setInterval() takes a function argument that will run an infinite number of times with a given millisecond delay as the second argument.


1 Answers

setInterval() will run infinitely.

If you wish to terminate the 'loop' you can use clearInterval. For example:

var counter = 0;

var looper = setInterval(function(){ 
    counter++;
    console.log("Counter is: " + counter);

    if (counter >= 5)
    {
        clearInterval(looper);
    }

}, 1000);
like image 115
rochal Avatar answered Oct 11 '22 12:10

rochal