Skip to main content

Command Palette

Search for a command to run...

Difference Between setTimeout and setInterval

Published
•1 min read•View as Markdown
Difference Between setTimeout and setInterval

setTimeout and setInterval are both JavaScript functions that can be used to schedule code to be executed after a certain period of time. The main difference between the two is how they behave:

  1. setTimeout is a one-time function that executes a piece of code after a specified amount of time (in milliseconds) has passed.

     setTimeout(function() {
       console.log("Hello after 3 seconds");
     }, 3000);
    
    1. setInterval is a repeating function that executes a piece of code repeatedly after a specified amount of time has passed.

       setInterval(function() {
         console.log("Hello every 3 seconds");
       }, 3000);
      

      In both cases, you can stop the execution of the scheduled code by using the clearTimeout or clearInterval function, respectively, and passing in the value returned by the original setTimeout or setInterval call.