‘setInterval()’ and ‘setTimeout()’ are two JavaScript methods that can be used to schedule code to run at a specific time or after a certain period of time has passed.

‘setInterval()’ repeatedly calls a function or evaluates an expression at specified intervals (in milliseconds). It returns an ID that can be used to clear the interval with the ‘clearInterval()’ method.

‘setTimeout()’ calls a function or evaluates an expression after a specified amount of time (in milliseconds). It returns an ID that can be used to clear the timeout with the ‘clearTimeout()’ method.

Example:

let intervalId = setInterval(myFunction, 3000);
function myFunction() {
  console.log("Hello");
}

This will call the ‘myFunction’ after every 3 sec

let timeoutId = setTimeout(myFunction, 3000);
function myFunction() {
  console.log("Hello");
}

This will call the ‘myFunction’ after 3 sec once

Also Read:

Categorized in: