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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With