this post was submitted on 08 Jul 2023
1 points (100.0% liked)

JavaScript

1968 readers
1 users here now

founded 1 year ago
MODERATORS
 

Hi, I need to create a infinite (but breakable) cycle where I can slow down the cycle by awaiting promises inside. While cycle should be able to do this, but as you can see in the image, the duration is all over the place.

Why is this happening? Is there a way to make it close to the original sleep duration?

top 3 comments
sorted by: hot top controversial new old
[–] pe1uca@lemmy.pe1uca.dev 1 points 1 year ago (1 children)

JS is a single threaded language, so there's just one long line of instructions, there's no actual background tasks.
A promise just runs at the next available slot the event loop provides so it's just as soon as it can run.

In this case I'm guessing other part of the code running in your JS engine is blocking the event loop preventing your code to run just after one second.

Where are you running it? Browser or server?
Are you using a framework? If so, have you tried just this piece of code without any other imported code?

[–] pe1uca@lemmy.pe1uca.dev 1 points 1 year ago* (last edited 1 year ago)

Here's a talk at JSConf to help understand this

Jake Archibald on the web browser event loop, setTimeout, micro tasks, requestAnimationFrame, ...
https://youtu.be/cCOL7MC4Pl0

[–] charolastra@programming.dev 1 points 1 year ago

Pretty consistent defining/running directly in the console on a blank tab in Firefox