-4

I tried to figure out the problem but this code logs twice. It logs John before the delay and "Robert" after the delay.

let myName = 'John';
delayer();
myName = 'Robert';
function delayer() {
    console.log(myName);
    setTimeout(() => console.log(myName), 1500)
}
Nathan Champion
  • 1,291
  • 1
  • 14
  • 23
  • 3
    Well, what do you think `setTimeout` does? – ikegami Oct 19 '21 at 14:39
  • Step through it with a debugger. https://stackoverflow.com/questions/10638059/javascript-debugging-line-by-line-using-google-chrome – Heretic Monkey Oct 19 '21 at 14:39
  • What do you mean by “log out an assignment”? What else do you expect to happen? Have you read the [documentation](//developer.mozilla.org/docs/Web/API/setTimeout)? – Sebastian Simon Oct 19 '21 at 14:40
  • 1
    `setTimeout(() => console.log(myName), 1500)` does not store the value at that moment in time. When it executes it reads the variable. Since you changed it before it executes, you have the updated value. – epascarello Oct 19 '21 at 15:06
  • @SebastianSimon I was asking about why two different results would be returned even though the variable has one value which is either the first assigned value or the second assigned value – Ahmed Afify Oct 19 '21 at 18:28
  • @epascarello thank you so much, you made it much clearer for me – Ahmed Afify Oct 19 '21 at 18:29
  • @HereticMonkey thank you, I'll look into that – Ahmed Afify Oct 19 '21 at 18:30

1 Answers1

2

() => console.log(myName) is the same as function() { return console.log(myName); }.[1]

The resulting function reference is passed to setTimeout which arranges to call it after the specified delay. setTimeout doesn't wait for the delay to occur before returning. It returns immediately. So myName has been changed by the time the anonymous function has been called.


  1. There are differences between the two approaches as itemized in the first link, but they don't come into play here.
ikegami
  • 367,544
  • 15
  • 269
  • 518