The global setTimeout()
method sets a timer which executes a function or specified piece of code once the timer expires.
Syntax
- function – a function containing a block of code.
- milliseconds – the time after which the function is executed.
- The
setTimeout()
method returns an intervalID, which is a positive integer.
Ex:
1 2 3 4 5 6 7 8 | //Display a Text Once After 3 Second // program to display a text using setTimeout method function greet() { console.log('Hello world'); } setTimeout(greet, 3000); console.log('This message is shown first'); |
Output:
1 2 | This message is shown first Hello world |
The program displays the text ‘Hello world’ only once after 3 seconds.
Note:
ThesetTimeout()
method is useful when you want to execute a block of once after some time.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // program to display time every 3 seconds function showTime() { // return new date and time let dateTime= new Date(); // returns the current local time let time = dateTime.toLocaleTimeString(); console.log(time) // display the time after 3 seconds setTimeout(showTime, 3000); } // calling the function showTime(); |
Output:
1 2 3 4 5 | 5:45:39 PM 5:45:43 PM 5:45:47 PM 5:45:50 PM .................. |
The above program displays the time every 3 seconds.
Note:
If you need to execute a function multiple times, it’s better to use thesetInterval()
method.
clearTimeout()
The program executes a block of code after the specified time interval. If you want to stop this function call, you can use the clearTimeout()
method.
Syntax:
- The
intervalID
is the return value of thesetTimeout()
method.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //Use clearTimeout() Method // program to stop the setTimeout() method let count = 0; // function creation function increaseCount(){ // increasing the count by 1 count += 1; console.log(count) } let id = setTimeout(increaseCount, 3000); // clearTimeout clearTimeout(id); console.log('setTimeout is stopped.'); |
Output:
1 | setTimeout is stopped. |
Note:
You generally use theclearTimeout()
method when you need to cancel thesetTimeout()
method call before it happens.
You can also pass additional arguments to the setTimeout()
method. The syntax is:
- When you pass additional parameters to the
setTimeout()
method, these parameters (parameter1
,parameter2
, etc.) will be passed to the specified function.
Ex:
1 2 3 4 5 6 7 | // program to display a name function greet(name, lastName) { console.log('Hello' + ' ' + name + ' ' + lastName); } // passing argument to setTimeout setTimeout(greet, 1000, 'John', 'Doe'); |
Output:
1 | Hello John Doe |