I was recently asked to debug the following block of code and ask what would be the output:
setTimeout(function() {
console.log(1);
}, 20);
setTimeout(function() {
console.log(2);
}, 10);
setTimeout(function() {
console.log(3);
}, 0);
setTimeout(console.log(4), 30);
console.log(5);
According to my understanding, setTimeout()
only takes callback functions and a delay time and so setTimeout(console.log(4), 30);
would give an error of some sort (since this setTimeout only takes an expression) and nothing would be logged in the console. But when tested in browser console, the output was
4
5
3
2
1
Any help would be appreciated in explaining why setTimeout(console.log(4), 30);
just prints out the 4 and moves onto console.log(5);
.