What is setTimeout() Method in javascript?


 setTimeout()

This is one of the many timing events. The window object allows the execution of code at specified time intervals. This object has provided SetTimeout() to execute a function after a certain amount of time. It takes two parameters as arguments. One is the function and the other is the time that specifies the interval after which the function should be executed.

syntax

window.setTimeout(function, milliseconds);

Example-1

In the following example, the time passed to the setTimeout() function is 2 seconds. Therefore the function will be executed after two secs and display the output as shown.

Live Demo

<html>
<body>
<p>wait 2 seconds.</p>
<script>
   setTimeout(function(){
      document.write("Tutorix is the best e-learning platform");
   }, 2000);
</script>
</body>
</html>

Output

wait 2 seconds
Tutorix is the best e-learning platform


Example-2

In the following example, the time passed to the setTimeout() function is 3 seconds. Therefore the function will be executed after three secs and display the output as shown.

Live Demo

<html>
<body>
<p id = "time"></p>
<script>
   setTimeout(function(){
      document.getElementById("time").innerHTML = "Tutorix is the product of Tutorialspoint";
   }, 3000);
</script>
</body>
</html>

Output

Tutorix is the product of Tutorialspoint.

Updated on: 05-Aug-2019

334 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements