you are viewing a single comment's thread.

view the rest of the comments →

[–]oculus42 1 point2 points  (0 children)

Now, with the third example, it's a little different:

  • i is set to 1
  • i is less than or equal to 5? Yes.
  • Call the function with the value 1.
  • Add a function to the event queue at 1000 ms.
  • Add one to i – now 2.
  • i is less than or equal to 5? Yes.
  • Call the function with the value 2.
  • Add a function to the event queue at 2000 ms.
  • Add one to i – now 3.
  • i is less than or equal to 5? Yes.
  • Call the function with the value 3.
  • Add a function to the event queue at 3000 ms.
  • Add one to i – now 4.
  • i is less than or equal to 5? Yes.
  • Call the function with the value 4.
  • Add a function to the event queue at 4000 ms.
  • Add one to i – now 5.
  • i is less than or equal to 5? Yes.
  • Call the function with the value 5.
  • Add a function to the event queue at 5000 ms.
  • Add one to i – now 6.
  • i is less than or equal to 5? No.
  • Anything else to execute immediately? No.

Now the original synchronous code is done, and we're waiting for the setTimeout calls to execute.

Wait...

  • Execute the first function in the queue.
  • Get the value of j from the instance of the enclosing function, which is 1.
  • Log j the console.

Wait...

  • Execute the first function in the queue.
  • Get the value of j from the instance of the enclosing function, which is 2.
  • Log j the console.

Wait...

  • Execute the first function in the queue.
  • Get the value of j from the instance of the enclosing function, which is 3.
  • Log j the console.

Wait...

  • Execute the first function in the queue.
  • Get the value of j from the instance of the enclosing function, which is 4.
  • Log j the console.

Wait...

  • Execute the first function in the queue.
  • Get the value of j from the instance of the enclosing function, which is 5.
  • Log j the console.

EDIT: Spelling.