setTimeout(), setInterval(), setImmediate()

muthu raja - Oct 16 - - Dev Community

1. setTimeout()

Purpose:
Executes a function or a piece of code once after a specified delay (in milliseconds).

Syntax:

  setTimeout(function, delay, [arg1, arg2, ...]);
Enter fullscreen mode Exit fullscreen mode

Parameters:
function: The function you want to execute after the delay.
delay: Time in milliseconds after which the function will
be executed.
arg1, arg2, ...: Optional additional arguments that can be
passed to the function when it is called.

Example:

setTimeout(() => {
   console.log('This message will be displayed after 2 
   seconds');
  }, 2000);
Enter fullscreen mode Exit fullscreen mode

Use Case:
Useful for running code after a delay, like showing a
message, changing UI after a specific time, or delaying API
calls.

2. setInterval()

Purpose:
Executes a function or a piece of code repeatedly at
regular intervals (in milliseconds) until it is stopped.

Syntax:

setInterval(function, delay, [arg1, arg2, ...]);
Enter fullscreen mode Exit fullscreen mode

Parameters:
function: The function you want to execute repeatedly.
delay: Time in milliseconds between each execution of the
function.
arg1, arg2, ...: Optional additional arguments that can be
passed to the function when it is called.

Example:

const intervalId = setInterval(() => {
  console.log('This message is displayed every 1 second');
 }, 1000);

  // To stop the interval
  setTimeout(() => clearInterval(intervalId), 5000); // Stops 
  after 5 seconds
Enter fullscreen mode Exit fullscreen mode

Use Case:
Ideal for running a piece of code repeatedly, like updating
a clock, sending heartbeats to a server, or periodically
checking a condition.

3. setImmediate()

Purpose:
Executes a function immediately after the current event
loop phase completes.

Note:
setImmediate() is only available in Node.js, not in the
browser.

Syntax:

setImmediate(function, [arg1, arg2, ...]);
Enter fullscreen mode Exit fullscreen mode

Parameters:
function: The function to be executed immediately after the
current event loop ends.
arg1, arg2, ...: Optional additional arguments to be passed
to the function.

Example:

setImmediate(() => {
   console.log('This runs after the current event loop 
   phase.');
  });
  console.log('This runs first.');
Enter fullscreen mode Exit fullscreen mode

Output:
This runs first.
This runs after the current event loop phase.
`
Use Case:
Typically used in Node.js to defer a task until the next
iteration of the event loop, often for I/O operations,
without blocking the current execution.

Differences:

setTimeout(): Executes code once after a specified delay.
setInterval(): Executes code repeatedly at specified
intervals.
setImmediate(): Executes code immediately after the current
event loop in Node.js.
Let me know if you'd like more examples or further details!

. . . . . . . . . . . . . . .