0

Due to event loop, async code like timeout executes when callstack is empty. But if body of a function takes longer time than a timeout, how to be sure about timeout stuff would run in after spesific duration?

For example, in code below

console.log("start"

setTimeout(()=>{
    console.log("do some timeout stuf"))
},1000)

for(let i = 1; i < 10000000000; i++){
    //some long-lasting stuff
}

console.log("end")

even if for loop executes in more than 1 second. timeout callback is run after program reaches to end. How to get "do some timeout stuff" input in first second?

I could not find any solution

  • 1
    Your "long-lasting" code is probably blocking the event loop from running the timer callback. – Pointy Jun 20 '23 at 20:37
  • `,[1000]` setimeout does not use an array..... – epascarello Jun 20 '23 at 20:55
  • 1
    you can't do this - `setTimeout(someFunction, x)` does not mean "run this after exactly `x` milliseconds precisely", it means "add this to the event queue after `x` milliseconds", at which point it gets executed whenever it is scheduled, after any synchronous code and any functions previously in the event queue get executed. In practice the solution is simply to not have any code that runs synchronously for a noticeable time - this is bad practice and will also make the browser appear unresponsive to the user. It's hard to offer concrete advice without knowing what the actual task is. – Robin Zigmond Jun 20 '23 at 21:31
  • See also https://stackoverflow.com/questions/10739835/are-there-any-standards-for-mobile-device-web-browsers-in-terms-of-thread-sleeping or https://stackoverflow.com/questions/196027/is-there-a-more-accurate-way-to-create-a-javascript-timer-than-settimeout. If you have any kind of realtime requirements, common JS runtimes (particularly the browser) are probably the wrong environment. – Bergi Jun 20 '23 at 21:58

1 Answers1

-1

javascripts is work in one thread that mean it's can do one thing at a time. the setTimeout will count 1 sec but even if the code not end after 1 sec it's will always run after all the code done.

this called the event loop, every async function will add to queue and that queue will start to handle after all the sync code complete.

for example:

console.log(1);
setTimeout(() => {
    console.log(2);
}, 100);
for (let i = 0; i < 10000000000; i++) {
    //do nothing
}
console.log(3);

it's will work as:

1- output 1

2- start timeout that will end after 100ms

3- start for loop (lets say it's will end after 1s)

4- output 3

5- timeout have been finished so the callback function will trigger (aka output 2)