Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a Javascript function (without promises) guaranteed to run without interruption?

Tags:

javascript

For example:

let x = 1
setInterval(() => x += 1, 1000)
function f() {
    console.log(x)
    console.log(x)
}

When the function is called, are two outputs guaranteed to be the same? Or can the setInterval trigger between these two?

I have tried to search MDN web docs on this topic, but I'm unfamiliar with the concept and unsure which pages I should be looking for.

like image 768
ssamtkwon Avatar asked May 20 '26 10:05

ssamtkwon


2 Answers

Your JavaScript process can be interrupted at any time by the CPU switching threads. However, JavaScript itself is single-threaded, and a function will never be interrupted by some other part of your application.

Extending your code slightly:

let x = 1
setInterval(() => x += 1, 1000)
function f() {
    console.log(x)
    while(1) { /* Program blocks forever, setInteral is never invoked again */ }
    console.log(x)
}

This program will cause the JavaScript runtime to hang forever, and your setInterval callback will never run. However the computer will continue to run other programs around yours, periodically pausing the JavaScript runtime so other processes can use the CPU.

like image 113
meagar Avatar answered May 22 '26 00:05

meagar


The setInterval callback won’t run until the call stack is empty, so I would expect x to be consistent at the time of each console call.

(I say “at the time of the call” because console.log output itself is not necessarily synchronous, making it possible to modify an object between the time console.log is invoked and the time that output actually appears in the console.)

like image 24
ray hatfield Avatar answered May 22 '26 00:05

ray hatfield