Difference between setinterval and settimeout

In this article you will learn what is setinterval and settimeout and what is defference between them with example.

Setinterval

SetInterval is used to execute a function repeatedly at a specified interval.

For example, if you call setInterval(myFunction, 1000), myFunction will be executed every 1 second until clearInterval is called.

let count = 0;

function incrementCount() {
  count++;
  console.log(`The count is now ${count}.`);
}

setInterval(incrementCount, 1000); // executes the incrementCount function every second


Settimeout

SetTimeout is used to execute a function once after a specified delay.

For example, if you call setTimeout(myFunction, 5000), myFunction will be executed once after 5 seconds.

function greet() {
  console.log("Hello!");
}

setTimeout(greet, 5000); // executes the greet function after a delay of 5 seconds

Note - setTimeout is used to delay the execution of a function once, while setInterval is used to repeatedly execute a function at a fixed interval.

kabeer

Edited  Feb 19, 06:03 pm

Article tags

×
SignUp with Email
X