Difference Between setInterval() and setTimeout()

Difference Between setInterval() and setTimeout()

In this blog, we will learn the difference between setTimeout() and setInterval() timing methods of JavaScript. Sometimes there is a need to execute our function at a certain period of time.

In JavaScript there are two timing methods available:

  1. setTimeout()
  2. setInterval()

setTimeout(): This method is used to call our function after a specified number of milliseconds.

Syntax:

window.setTimeout(function, milliseconds);


Example1:


<!DOCTYPE html>
<html>
<body>
 
 
<script>
 
setTimeout(myFunction, 3000);
 
function myFunction() {
  console.log('Hello');
}
</script>
 
</body>
</html>
 


In this example, we have created a function myFunction() and then used the setTimeout() method to call this function after 3 seconds.


Example2:


<!DOCTYPE html>
<html>
<body>
 
 
<script>
 
setTimeout(function()
{
  console.log('Hello');
}, 3000);
 
</script>
 
</body>
</html>
 


In this example, we have used an anonymous function to use setTimeout method. We have two options we can use a separate function to use setTimeout() or we can use an anonymous function.  



setInterval():
This method is used to call a function continuously after a specified number of milliseconds.

Syntax:


window.setInterval(function, milliseconds);


Example1:


<!DOCTYPE html>
<html>
<body>
 
 
<script>
 
setInterval(myFunction, 3000);
 
function myFunction() {
  console.log('Hello');
}
</script>
 
</body>
</html>
 


In this example setInterval() method will call a function myFunction() continuously after 3 second.


Example2:


<!DOCTYPE html>
<html>
<body>
 
 
<script>
 
setInterval(function()
{
  console.log('Hello');
}, 3000);
 
</script>
 
</body>
</html>


In this example, we have used the anonymous function.


By using timing methods we can create a number of useful examples some of the following:

  1. Open POP UP box after a specified number of second
  2. automatic image slideshow