Intervals and Timeouts
Sometimes, we want to run a chunk of code on a specific schedule. For example, maybe we wish to "ping" our server every 10 seconds, to check for new data.
We can do this using window.setInterval
:
window.setInterval( () => { pingServer(); }, 10 * 1000);
The first argument is a function that contains the code we want to run. The JavaScript engine will call this function over and over again, based on the interval duration.
The second argument is the interval duration, in milliseconds. In this case, we've specified 10 * 1000
, which resolves to 10,000 milliseconds, or 10 seconds.
Putting these two together, the pingServer
function will be called every 10 seconds.
Cancelling intervals
By default, an interval will run forever, until the user closes the tab or refreshes the page.
We can cancel an interval using the clearInterval
method:
const intervalId = window.setInterval(() => { pingServer();}, 10 * 1000);
// When I'm ready to stop the interval, I'd run:window.clearInterval(intervalId)
Whenever we create an interval with setInterval
, the JavaScript engine automatically assigns it a unique ID and provides it to us.
We can then call the clearInterval
method with this ID, whenever we wish to stop the interval.
Because it's possible to have multiple intervals running at the same time, we need to specify which interval we're trying to cancel. That's why we need the ID.
Timeouts
The setInterval
function will call the provided callback over, and over, and over. But what if we only need it to be called once?
setTimeout
is identical to setInterval
in every way, except it only calls the function a single time, after a provided delay.
window.setTimeout( () => { console.log('10 seconds have passed!') }, 10 * 1000);
As with setInterval
, we can cancel a pending timeout with clearTimeout
:
const timeoutId = window.setTimeout( () => { console.log('10 seconds have passed!') }, 10 * 1000);
window.clearTimeout(timeoutId)
If clearTimeout
is called before the time has expired, the timeout will be cancelled, and the callback function will never be called. if we try to call clearTimeout
after the time has expired, it has no effect.