# JavaScript Timers

##Timeouts

When you want to run a function after a specific time delay then setTimeout is the built-in function to accomplish this.

setTimeout(myFunc, 3000); //call the function myFunc after 3000ms
setTimeout(function() {
  alert('hi');
}, 2500); //run the anonymous function after 2500ms
setTimeout('myFunc()', 1000); //call the function myFunc after 1 second
window.setTimeout(myFunc, 300); //same as first example
1
2
3
4
5
6

# Intervals

When you want to run something repeatedly after a set time, for example, once every ten seconds, then setInterval is the function to call.

Timers running on intervals can be stopped if you call the clearInterval( ) method. Just make sure that you keep a reference to the interval.

let intervalId = setInterval( myFunc, 3000);
//keep calling myFunc every 3 seconds
....
//use the intervalId to stop the interval calls running
clearInterval( intervalId );
1
2
3
4
5

# Recursive Timeouts

Another way to approach timed intervals is with a recursive call to the setTimeout function. Inside the function that runs following your setTimeout, you make another call to the same function. The process repeats itself.

The difference with the recursive calls is that it allows us to change the amount of time between the calls or stop it after any call.

We can use this method to create ever shorter time spans between callbacks or random times between callbacks.

Back to Week 9 main page

Last Updated: 11/1/2020, 2:12:38 PM