What is setTimeout in JavaScript
February 14, 2020
What is setTimeout in JavaScript
in this tutorial, you will learn how to use the JavaScript setTimeout()
that sets a timer and executes a callback function after the timer expires.
setTimeout() is a function which executes another function or specified piece of code after waiting for the specified time delay in milliseconds.
The setTimeout
function expects 2 arguments: a reference to a callback function and a delay in milliseconds. The following will print a message to the console after 1 second:
setTimeout(() => {
console.log('BitFrit !!!!');
}, 1000);
The above example uses an inline function expression, but we could just as well reference a function by its name:
const BitFrit=(Params)=> {
console.log(Params,'BitFrit !!!!');
}
const BitFritTimer=
setTimeout( () => { BitFrit("Hello")}
,1000)
//OUTPUT "Hello" "BitFrit !!!!"
Cancelling a timer
The setTimeout
function returns a timer id that can then be passed to the global clearTimeout
function to cancel the timeout. Take the following example:
const BitFrit=(Params)=> {
console.log(Params,'BitFrit !!!!');
}
const BitFritTimer=
setTimeout( () => { BitFrit("Hello")}
,1000)
setTimeout(() => {
console.info('Funciton is clear and Stop To Print Hello BitFrit')
clearTimeout(BitFritTimer);
}, 100);
//OUTPUT Funciton is clear and Stop To Print Hello BitFrit