Timeouts and Intervals
Table of Contents
Timeouts and intervals allow you to control when and how often a function is invoked. The two are similar in usage but their functionalities are different, and we'll learn the difference between timeout and interval, along with how to cancel, or clear, them when we are done with them.
Set Timeout
A timeout lets you run a function after a certain amount of time has elapsed. This is done with the setTimeout
function that takes as its parameters the function to run and in how much time into the future (in milliseconds). The function will be invoked once the time has elapsed.
For example, you can set a timeout to make a function execute five seconds into the future:
JAVASCRIPTfunction sayHello() {
console.log("Hello!");
}
const timeout = setTimeout(sayHello, 5 * 1000);
HTMLHello!
- JavaScript
If you run the code, you will notice that the logging will not happen until five seconds pass. That's the power of timeouts, being able to run code in the future.
Clear Timeout
So what if we change our mind about running that function in the future? We can clear it using the clearTimeout
function. This function takes the timeout as its parameter and cancels it.
Let's say we set it to print but immediately change our minds:
JAVASCRIPTfunction sayHello() {
console.log("Hello!");
}
const timeout = setTimeout(sayHello, 5 * 1000);
clearTimeout(timeout);
Because we used clearTimeout
on our timeout, it was cleared and no longer active. It will basically act as if it never existed and therefore nothing will get printed on the screen.
Set Interval
Intervals are a simpler way of making the same code repeat over and over again, with a set amount of time in between, the interval time. You can think of intervals as basically timeouts that call themselves at the end to start the cycle all over again.
Let's create an interval using setInterval
to build a basic timer:
JAVASCRIPTlet seconds = 0;
function printTime() {
seconds++;
console.log("Seconds elapsed: " + seconds);
}
const interval = setInterval(printTime, 1000);
HTMLSeconds elapsed: 1
Seconds elapsed: 2
Seconds elapsed: 3
Seconds elapsed: 4
Seconds elapsed: 5
- JavaScript
We are calling printTime
once every second and inside that function we are both incrementing the seconds
variable and printing it out. As this continues on, it serves as a basic way to keep track of how much time has passed since the page has loaded.
Clear Interval
As with clearTimeout
, clearInterval
is a way you can clear your intervals and prevent it from continuing on forever. Sticking with our timer example, let's say you wanted to stop repeating once you hit 10 seconds.
JAVASCRIPTlet seconds = 0;
function printTimeUntil10() {
seconds++; // increment seconds by 1
console.log("Seconds elapsed: " + seconds);
if (seconds === 10) {
console.log("10 seconds has elapsed!")
clearInterval(interval); // we're done, clear it!
}
}
const interval = setInterval(printTimeUntil10, 1000);
HTMLSeconds elapsed: 1
Seconds elapsed: 2
Seconds elapsed: 3
Seconds elapsed: 4
Seconds elapsed: 5
Seconds elapsed: 6
Seconds elapsed: 7
Seconds elapsed: 8
Seconds elapsed: 9
Seconds elapsed: 10
10 seconds has elapsed!
- JavaScript
We have a nifty condition that checks if we finally hit 10 seconds, and once we do, we clear the interval so it stops repeating and print out a nice message letting us know that we hit the desired number of seconds.
- Getting Started with TypeScript
- Create an RSS Reader in Node
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Creating a Twitter bot with Node.js
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue