DEV Community

Adrian Matei for Codever

Posted on • Edited on

Javascript runtime interview question

I would definitely put the following question in an interview, if am interested in knowing if the candidate knows a bit about the Javascript runtime.

What is the order in which the following texts are logged via console.log?

console.log('1 - start');
setTimeout(() => console.log('2 - setTimeout1'), 0);
Promise.resolve('Success')
    .then(()=> console.log('3 - promise1'))
    .then(()=> console.log('4 - promise2'));
setTimeout(() => console.log('5 - setTimeout2'), 0);
console.log('6 - end');
Enter fullscreen mode Exit fullscreen mode

If you are not sure about the answer read this In depth: Microtasks and the JavaScript runtime environment article before


Output

1 - start// statement is executed directly in the script (first "Run script" task)
5 - end // part of the first "Run script" task gets executed too
3 - promise1 // placed in microTasks queue and executed between tasks, after first "Run script" task is ready
4 - promise2 // microtask added  during previous microtask execution  and executed immediately
2 - setTimeout1 // callback execution scheduled in another task in the "macroTasks" queue (also task queue), executed in the next interation of the event-loop
5 - setTimeout2 // callback execution scheduled in another task in the task queue, executed in the next iteration of event-loop
Enter fullscreen mode Exit fullscreen mode

Usually it takes a couple of milliseconds in this case before scheduling and execution of the statements in setTimeout. So even if you set the value ov 1 in the first setTimeout, it will still be shown before. Play around with it to see where is the limit for your system:

console.log('1 - start');
const timeScheduled = Date.now();
setTimeout(() => console.log(`2 - setTimeout1 ${Date.now()-timeScheduled}ms have passed since I have been scheduled`), 1);
Promise.resolve('Success')
    .then(()=> console.log('3 - promise1'))
    .then(()=> console.log('4 - promise2'));
setTimeout(() => console.log(`5 - setTimeout2 ${Date.now()-timeScheduled}ms have passed since I have been scheduled`), 0);
console.log('6 - end');
Enter fullscreen mode Exit fullscreen mode

Shared with ❤️ from Codever.   👉   use the copy to mine functionality to add it to your personal snippets collection.

Top comments (0)