Search code examples
javascriptblockingsynchronous

Javascript: variable declared inside arrow function can't be updated within while loop


In essence I'm trying to run a simple arrow function, testing synchronous and blocking code in Javascript. Here is the code snippet:

let runTimer = (startingTime) => {
  let time = parseInt(startingTime);
  while (time < 100) {
    console.log("testing", time);
    time = time++;
  }
};

runTimer(0)
console.log("timer complete");

What's happening is that time variable never got updated inside while loop hence causing an infinite loop. I've also tried making use of var instead of let while declaring time variable but no success. Even changing the arrow function to a normal function declaration is not the making any difference. I wonder what would be the good reason for this and how can I change this code snippet to have a finite loop followed by logging timer complete to the console.


Solution

  • The problem is

    time = time++;
    

    This is using post-increment, which means that value the increment expression resolves to is before the change to the variable takes place. The logic that takes place is very similar to the following:

    time = (() => {
      const origTime = time;
      time = time + 1;
      return origTime;
    })();
    

    This resolves to time = time. Although the increment updates the variable, the original value is then assigned to time again, so it appears to stay unchanged.

    I'd recommend against using increments as expressions anyway, they're confusing and can produce bugs like these. Just do time++:

    let runTimer = (startingTime) => {
      let time = parseInt(startingTime);
      while (time < 100) {
        console.log("testing", time);
        time++;
      }
    };
    
    runTimer(0)
    console.log("timer complete");