Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading