bsb21
bsb21

Reputation: 55

How does setInterval() run independently of sequential execution?

I'm a beginner in software development. To my knowledge, JavaScript runs sequentially from left to right, top to bottom, only skipping lines and returning carriages when functions are called. If that's the case, how can a program remember to run a setInterval function set to execute every 2000ms when it's currently occupied with other calculations?

Upvotes: 0

Views: 407

Answers (2)

Ben Aston
Ben Aston

Reputation: 55739

Although each JavaScript agent has a single executing thread - the so-called "event loop" - the runtime is not limited in the number of threads of execution it may use to service this.

Callbacks passed to functions such as setInterval, setTimeout, or requestAnimationFrame, are scheduled to be run by "magic" (ie. hidden logic) within the JavaScript runtime environment.

This hidden logic schedules the insertion of callbacks on job queues, at appropriate times (eg. after an interval has elapsed). When a job associated with a callback reaches the front of the relevant job queue, and when the executing thread is available to service it, the job is removed from the queue, a stack frame (aka execution context) is instantiated for it, pushed onto the call stack, and execution begins.

The logic for asynchronous functions such as setTimeout, setInterval and requestAnimationFrame are defined in other specifications (eg. W3C/WHATWG), and implemented by host applications (eg. a web browser or a NodeJS instance). These functions are not defined by the ECMAScript specification.

Asynchronous promise behavior, on the other hand, is specified within the ECMAScript specification.

Upvotes: -1

William
William

Reputation: 751

Behind the scenes, there is a queue of “tasks” that JavaScript should run (the event loop). Tasks are functions. At the end of a function, JavaScript checks the queue to see if another function should be called.

setInterval only pushes functions into this queue, to be run at specified time.

JavaScript only has 1 thread, so if a heavy computation takes up a lot of time, events in the queue will be postponed until that task has completed.

This is why you do not want to run a blocking function in JS.

Upvotes: 3

Related Questions