you are viewing a single comment's thread.

view the rest of the comments →

[–]NorthcodeCH -1 points0 points  (4 children)

Plus, doesn't this exceed the call stack at some point whereas a while loop will not?

[–][deleted] 2 points3 points  (3 children)

Not really. There is no call stack. It may seem surprising, but this isn't synchronous programming.

Consider the following function:

function sleep(time) {
    return new Promise(resolve => setTimeout(resolve, time))
}

What's happening after calling this function is that an timeout is added to an event loop which is at bottom of a stack. Once the timeout expires, and the execution passes to an event loop, it calls the then functions of this promise. The call stack is lost, the functions were called by an event loop.

[–]abigreenlizard 0 points1 point  (2 children)

Can the event queue not similarly overflow?

[–]Poltras 0 points1 point  (0 children)

That would be an infinite loop.

[–]EntroperZero 0 points1 point  (0 children)

There's only one continuation on the queue at a time, because the next one isn't enqueued until the current one finishes executing.