3

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?

9
  • 1
    That looks like it increments w. Simplified let x = w+w
    – zer00ne
    Sep 11, 2016 at 20:14
  • @zer00ne But w is not a variable, it's just a parameter referring to some other variable. Probably the window object. Why would calling the function increase anything?
    – XCS
    Sep 11, 2016 at 20:15
  • @self What context? This is all the code, run it in your browser console in a new tab.
    – XCS
    Sep 11, 2016 at 20:15
  • like self is saying, setTimeout returns a value which is reflected in console. I would've never have experienced such an issue, I have a tendency to declare all vars upfront overzealously.
    – zer00ne
    Sep 11, 2016 at 20:22
  • 1
    @DanPantry that's becaused the undefined value isn't a function. console.log returns undefined, most likely the browser runtime is just ignoring the fact that it isn't a function
    – Ryan
    Sep 11, 2016 at 20:34

1 Answer 1

10

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.

5
  • Oh my God, you are right. I always thought that was the logged value, I was ignoring the function... log in the console which was actually logging the x function. :)
    – XCS
    Sep 11, 2016 at 20:17
  • 1
    Tbh, this was actually pretty hard to notice, great bug-spotting techniques you got there :D
    – XCS
    Sep 11, 2016 at 20:18
  • 1
    Glad it helped!
    – Ryan
    Sep 11, 2016 at 20:22
  • @Cristy I would encourage you to accept my answer :)
    – Ryan
    Sep 12, 2016 at 17:32
  • Yeah, sorry, I forgot :D
    – XCS
    Sep 13, 2016 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.