javascript tutorial - [Solved-5 Solutions] setTimeout or setinterval ? - javascript - java script - javascript array



Problem:

As far as we can tell, these two pieces of javascript behave the same way:

Option A:

function myTimeoutFunction()
{
    doStuff();
    setTimeout(myTimeoutFunction, 1000);
}

myTimeoutFunction();
click below button to copy the code. By JavaScript tutorial team

Option B:

function myTimeoutFunction()
{
    doStuff();
}

myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);
click below button to copy the code. By JavaScript tutorial team

Is there any difference between using setTimeout and setInterval ?

Solution 1:

  • They essentially try to do the same thing, but the setInterval approach will be more accurate than the setTimeout approach, since setTimeout waits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms (or a lot more if our function takes a long time to execute).
  • Altough one might think that setInterval will execute exactly every 1000ms, it is important to note that setInterval will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish.
  • we can clearly see that the timeout will fall behind, while the interval is almost all the time at almost 1 call/second (which the script is trying to do). If we change the speed variable at the top to something small like 20 (meaning it will try to run 50 times per second), the interval will never quite reach an average of 50 iterations per second.
  • The delay is almost always negligible, but if you're programming something really precise, we should go for a self-adjusting timer (which essentially is a timeout-based timer that constantly adjusts itself for the delay it's created)

Solution 2:

setInterval()

  • setInterval() is a time interval based code execution method that has the native ability to repeatedly run a specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless we call clearInterval().
  • If we want to loop code for animations or on a clock tick, then use setInterval().
function doStuff() {	
    alert("run our code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);
click below button to copy the code. By JavaScript tutorial team

setTimeout()

setTimeout() is a time based code execution method that will execute a script only one time when the interval is reached. It will not repeat again unless we gear it to loop the script by nesting the setTimeout() object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless we call clearTimeout().

function doStuff() {
    alert("run our code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);
click below button to copy the code. By JavaScript tutorial team

If we want something to happen one time after a specified period of time, then use setTimeout(). That is because it only executes one time when the specified interval is reached.

Solution 3:

The setInterval makes it easier to cancel future execution of our code. If we use setTimeout, we must keep track of the timer id in case we wish to cancel it later on.

var timerId = null;
function myTimeoutFunction()
{
    doStuff();
    timerId = setTimeout(myTimeoutFunction, 1000);
}

myTimeoutFunction();

// later on...
clearTimeout(timerId);
click below button to copy the code. By JavaScript tutorial team

versus

function myTimeoutFunction()
{
    doStuff();
}

myTimeoutFunction();
var timerId = setInterval(myTimeoutFunction, 1000);

// later on...
clearInterval(timerId);
click below button to copy the code. By JavaScript tutorial team

Solution 4:

We find the setTimeout method easier to use if we want to cancel the timeout:

function myTimeoutFunction() {
   doStuff();
   if (stillrunning) {
      setTimeout(myTimeoutFunction, 1000);
   }
}

myTimeoutFunction();
click below button to copy the code. By JavaScript tutorial team

Also, if something would go wrong in the function it will just stop repeating at the first time error, instead of repeating the error every second

Solution 5:

The very difference is in their purposes.

setInterval()
   -> executes a function, over and over again, at specified time intervals  
		
setTimeout()
   -> executes a function, once, after waiting a specified number of milliseconds
click below button to copy the code. By JavaScript tutorial team
  • It's as simple as that more elaborate details here

Related Searches to javascript tutorial - setTimeout or setinterval?