Account
Categories

setTimeout()


Definition:

It is used to set a time delay in a program. It works like a timer or an alarm.

When you write a program and want it to run after a few seconds, you can use setTimeout().

Now you will clearly understand with the help of the flowchart.

Start
  |
  v
Write your code inside setTimeout()
  |
  v
Set the time delay
  |
  v
Run the setTimeout() function
  |
  v
Wait for the given time
  |
  v
Code executes
  |
  v
End
  

Syntax:

setTimeout(function() {
 //This code will run after some time. 
}, time_in_milliseconds);

Example:

setTimeout(function() {
 console.log("Hello!");
}, 2000);

Output:

Hello!