Difference Between the JavaScript's setTimeout() and setInterval() Functions

In this article, you will learn the Difference Between JavaScript's setTimeout() and setInterval() functions. The main purpose of this tutorial is to give the IT/CS students and new programmers a reference to understand the usage and when to use the said JavaScript Functions. Here, snippets and a sample application source code that demonstrate the functionality of setTimeout and setInterval are provided.

What is the Difference Between JavaScript's setTimeout() and setInterval()?

JavaScript's setTimeout() and setInterval() functions have the same syntax of coding but different use. The setTimeout() executes an expression or a script once while the setInterval() executes the expression or script repeatedly. Check out the snippet below to have a better understanding.

Using JS setTimeout()

The below snippet demonstrates a simple setTimeout() script. It executes the certain script after the given timeout and it is only done once.

  1. window.load = function(){
  2.     setTimeout(()=>{
  3.         alert("This is a sample message");
  4.     },3000)
  5. }

When you add the script above to your web application, an alert/dialog will be shown 3 seconds after the page document is successfully loaded.

Using JS setTinterval()

The below snippet demonstrates how the setInteval() function works.

  1. window.load = function(){
  2.     setInterval(()=>{
  3.         location.reload();
  4.     },10000)
  5. }

Adding the simple script above to your web application enables your application to refresh or reload 10 seconds after the page document is successfully loaded.

When to use JavaScript's setTimeout() and setInterval()?

The setTimeout() and setInterval() usage depends on what logic you are targeting to create on your application client side. If you like to delay the execution of the script on your application and run it only once, setTimeout() is the best option for doing it. If you like to repeatedly execute a JS function or script, the setInterval() method is the best option. Also, to stop the interval, use the clearInterval() method.

Example

Here's a simple web application source code that demonstrates the usage of both setTimeout() and setInterval() methods.

Interface

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>JavaScript setTimeout vs setInterval</title>
  7.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9.     <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  10.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  11.  
  12.     <style>
  13.         html, body{
  14.             height: 100%;
  15.             width: 100%;
  16.         }
  17.         body{
  18.             display: flex;
  19.             height: 100%;
  20.             width: 100%;
  21.             flex-direction: column;
  22.         }
  23.         body>nav, body>footer{
  24.             flex-shrink: 1;
  25.         }
  26.         body>main{
  27.             flex-shrink: 1;
  28.             flex-grow: 1;
  29.             overflow: auto;
  30.             display: flex;
  31.             flex-direction: column;
  32.             width: 100%;
  33.             align-items: center;
  34.             justify-content: center;
  35.         }
  36.         pre{
  37.             min-height:20vh
  38.         }
  39.         .bigFont{
  40.             font-size:20px;
  41.         }
  42.     </style>
  43. </head>
  44. <body style="background:#eff3fc">
  45.     <nav class="navbar navbar-expand-lg navbar-dark" style="background:#495C83">
  46.         <div class="container">
  47.             <a class="navbar-brand" href="./">JavaScript setTimeout() vs setInterval()</a>
  48.             <div>
  49.                 <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  50.             </div>
  51.         </div>
  52.     </nav>
  53.  
  54.     <main class="container-fluid">
  55.         <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  56.             <h2 class="text-center">Comparison Between JavaScript's setTimeout() vs setInterval() </h2>
  57.             <hr>
  58.             <div class="card mt-3 rounded-0">
  59.                 <div class="card-body rounded-0">
  60.                     <div class="container-fluid">
  61.                         <div class="row justify-content-center">
  62.                             <div class="col-lg-8 col-md-10 col-sm-12 col-xs-12">
  63.                                 <div class="mb-3 text-center" id="displayContainer">
  64.                                 </div>
  65.                                 <div class="mb-3">
  66.                                     <div class="row">
  67.                                         <div class="col-lg-6 col-md-6 col-sm-12">
  68.                                             <button class="btn btn-primary rounded-pill w-100" type="button" id="settimeoutBtn">setTimeout</button>
  69.                                         </div>
  70.                                         <div class="col-lg-6 col-md-6 col-sm-12">
  71.                                             <button class="btn btn-success rounded-pill w-100" type="button" id="setintervalBtn">setInterval</button>
  72.                                         </div>
  73.                                     </div>
  74.                                    
  75.                                 </div>
  76.                             </div>
  77.                         </div>
  78.                     </div>
  79.                 </div>
  80.             </div>
  81.         </div>
  82.     </main>
  83. <footer class="container-fluid py-3" style="background:#495C83; color:#fff">
  84.     <div class="container-fluid my-2">
  85.         <div class="text-center">
  86.             <b>JavaScript setTimeout vs setInterval &copy; 2023</b>
  87.         </div>
  88.     </div>
  89. </body>
  90. <script src="./assets/script.js"></script>
  91. </html>

JavaScript

assets/script.js

  1. const settimeoutBtn = document.getElementById('settimeoutBtn')
  2. const setintervalBtn = document.getElementById('setintervalBtn')
  3. const displayContainer = document.getElementById('displayContainer')
  4.  
  5. /**
  6.     * setTimeout Example Script
  7.     * syntax
  8.     *  setTimeout(expression, timeout)
  9.     *  - timeout = (1 second = 1000)
  10.     */
  11. settimeoutBtn.addEventListener('click', function(){
  12.     displayContainer.innerText = "Please wait for 5 seconds."
  13.     setTimeout(()=>{
  14.         displayContainer.innerText = ""
  15.         alert("You have waited 5 second before this dialog been shown.")
  16.     }, 5000)
  17. })
  18.  
  19. /**
  20.     * setInterval Example Script
  21.     * syntax
  22.     *  setInterval(expression, timeout)
  23.     *  - timeout = (1 second = 1000)
  24.     */
  25. var interval;
  26. setintervalBtn.addEventListener('click', function(){
  27.     var is_started = setintervalBtn.getAttribute('is-started')
  28.     if(is_started == null || is_started == "false"){
  29.         setintervalBtn.setAttribute('is-started',"true")
  30.         is_started = true
  31.         setintervalBtn.innerText = "Stop Interval"
  32.         displayContainer.classList.add('bigFont')
  33.     }else{
  34.         displayContainer.classList.remove('bigFont')
  35.         setintervalBtn.setAttribute('is-started',"false")
  36.         is_started = false
  37.         setintervalBtn.innerText = "setInterval"
  38.     }
  39.    
  40.     if(is_started){
  41.         displayContainer.innerText = 0
  42.         var countdown = parseInt(displayContainer.innerText)
  43.         interval = setInterval(()=>{
  44.             countdown++;
  45.             displayContainer.innerText = countdown
  46.         }, 1000)
  47.     }else{
  48.         if(interval != undefined)
  49.         clearInterval(interval)
  50.     }
  51. })

The source code above will result in a simple web application page that contains 2 buttons. One of the buttons triggers/displays an alert dialog after 5 seconds. The other one is to trigger a simple countdown.

Snapshots

setTimeout vs setInterval of JavaScript

setTimeout vs setInterval of JavaScript

There you go. That's the end of this tutorial. I hope this setTimeout() vs setInterval() of JavaScript Tutorial will help you with what you are looking for and adds up to your knowledge of using JavaScript built-in methods.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment