Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code output consecutive numbers?

Tags:

javascript

I was trying to post a basic JS trick question, and it's apparently tricking me too :)

Run this in your console:

x = (w) => w.length;
setTimeout(console.log(x), 0);

The, each time you run setTimeout(console.log(x), 0); you get an increasing number. Why is that? Shouldn't the w parameter referrer to the window object?

like image 211
XCS Avatar asked Dec 28 '25 00:12

XCS


1 Answers

setTimout returns a value. You're seeing the timer id which is the returned value of setTimeout, which can used as the argument to a clearTimeout call.

The returned timeoutID is a numeric, non-zero value which identifies the timer created by the call to setTimeout(); this value can be passed to Window.clearTimeout() to cancel the timeout. [0]

[0] https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

The w parameter would not refer to the window object. console.log returns undefined, so your function would never get called.

like image 120
Ryan Avatar answered Dec 30 '25 14:12

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!