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
Categories: web designing javascript front end developer
Written By : Web Development Institute
Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing Expert Course

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 25 Days

Crash : 15 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 6 Months

Fastrack : 4 Months

Crash : 2 Months

Web Expert with Python

Regular : 12 Months

Fastrack : 6 Months

Crash : 3 Months

Related Blogs

Request For Demo