JavaScript setTimeout Examples
In this article, we will look at the traditional methods JavaScript has available for running code asynchronously after a settime period elapsed. Let’s see how to use JavaScript setTimeout function with examples.
setTimeout():
The setTimeout() function executes a particular block of code once after a specified time has elapsed. Let’s understand the parameters it accepts.
Syntax:
setTimeout(function, duration, param1, param2, ...)
The first parameter is a function to run or a reference to a function defined elsewhere. The second parameter is a number representing the duration in milliseconds to wait before executing the code. After the second parameter, we can pass in zero or more values that represent any parameters you want to pass to the function when it is run.
Ex:
function greet(){
console.log("Hello");
}
setTimeout(greet, 2000)
In the above code, we have a function ‘greet’ which logs ‘hello’ to the console, we can pass that function into setTimeout() function with duration of 2 seconds. So, the text ‘hello’ will be logged to the console after 2seconds.
function greet(name){
console.log("Hello $(name)')
}
setTimeout(greet, 2000, 'John')
If the greet() function were to accept a parameter like in the above example code, we can pass the parameter value as the third argument to setTimeout and after 2 second “hello John” will logged to the console.
Once setTimeout has been called sometimes you might want to cancel it. To clear a timeout, you can use clearTimeout() method passing in the identifier returned by setTImeout as a parameter.
Ex:
function greet(){
console.log("Hello");
}
const timoutId = setTimeout(greet, 2000, 'John')
clearTimeout(timoutId)
In the above code, we have assigned the return value from setTimeout to a constant called timoutId. Then we pass that Id into the clearTimeout method which will basically ensure our greet function will not run after the 2 second duration. So, nothing is logged to console as the greet() function never executes.
A more practical scenario is clearing timouts when the component is unmounting to free up the resources and also pre vent code from incorrectly executing on an unmounted component.