menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Programming News

>

How setTim...
source image

Medium

1M

read

114

img
dot

Image Credit: Medium

How setTimeout and setInterval Work in JavaScript

  • Timers in JavaScript, such as setTimeout and setInterval, are managed by the environment around JavaScript, not the engine itself.
  • When setTimeout is called, the function won't necessarily run exactly after the specified time but after it, depending on other tasks.
  • setInterval sets up a repeating schedule, adding functions to the task queue each time the timer fires.
  • If JavaScript is busy when setInterval fires again, the new task has to wait its turn, making it a reminder rather than immediate execution.
  • The passed delay in setTimeout and setInterval is a minimum; the function may run later due to timer scheduling and JavaScript's workload.
  • JavaScript adds timer functions to a queue of tasks which are executed when the current stack is empty.
  • Long-running synchronous code can delay timer callbacks as JavaScript completes the current tasks before moving to queued tasks.
  • setInterval may cause delays and skipped intervals if callbacks take too long, affecting the desired timing.
  • Modern browsers throttle timers in background tabs to save resources, potentially affecting the precision and consistency of timer execution.
  • The event loop controls when timer callbacks run, ensuring tasks are executed in the order they were added, based on JavaScript's workload.

Read Full Article

like

6 Likes

For uninterrupted reading, download the app