Member-only story
Mastering JavaScript’s setTimeout and clearTimeout Functions
If you’re a non-premium user, click here to read this article for free. If not, continue reading.
JavaScript is a powerful programming language that allows you to create dynamic and interactive websites. One of the most useful features of JavaScript is the ability to schedule code to run at a specific time in the future. This is done with the setTimeout() function.
The setTimeout() function is used to schedule a function to be called after a specified delay. The function takes two arguments: the function to be called and the delay in milliseconds. The function returns a timer ID, which can be used to clear the timeout with the clearTimeout() function.
Here is an example of how to use setTimeout() to display a message after a delay of 1000 milliseconds (1 second):
setTimeout(() => {
console.log("Hello, World!");
}, 1000);
In this example, the setTimeout() function is used to schedule the anonymous function that displays the message “Hello, World!” to be called after a delay of 1000 milliseconds.
Sometimes, you may want to cancel a scheduled timeout before it runs. This can be done with the clearTimeout() function. The clearTimeout() function takes one argument: the timer ID returned by the setTimeout() function.