Abraham
Abraham

Reputation: 15830

Sleep in javascript, why doesn't it loop?

I was wondering why the common code for sleep functionality for javascript doesn't loop

await new Promise(resolve =>{setTimeout(resolve, 5000)});

it assigns resolve an arrow function that runs resolve itself after 5 seconds. so why doesn't this recurse or loop?

Upvotes: 0

Views: 79

Answers (2)

Iyashi
Iyashi

Reputation: 582

resolve is a function, generated by Promise.

To put it simply, resolve internally marks the Promise as resolved.

But that only happens once. You cant resolve a Promise twice.

Once a Promise got resolved, it "triggers" (dunno, if it's the correct word) given then, catch, finally callbacks.

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1075597

There's just no reason for it to. The event system will trigger the call to resolve after approximately five seconds without any need for a loop, which will fulfill the promise.

Upvotes: 1

Related Questions