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

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.

>Solution :

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.

Leave a Reply