Reputation: 1179
This an Angular app, and this specific code is inside a webworker in Typescript. I'm still new to webworkers, but both the sleep and the loop execute inside the same thread.
The intent is to poll a service and exit the loop when a the process is completed. My problem is the sleep call below is not sleeping. I need it to delay for at least 9 seconds, and ideally I'd like it to be configurable. But it runs as though the sleep didn't run.
I have two questions:
Code below:
function sleep(ms: number) {
return new Promise((resolve) => {
log('DEBUG','Sleeping for ' + ms + ' ms');
setTimeout(resolve, ms);
});
}
while (jobIsStillRunning(jobExecutionResult)) {
postMessageWithLog(jobExecutionResult);
log('DEBUG','sendFilePolling() jobExecutionResult=' + JSON.stringify(jobExecutionResult));
sleep(30000); // Sleep function runs but doesn't do anything.
jobExecutionResult = await getAsyncFilesResult(jobExecutionResult);
}
Upvotes: 1
Views: 134
Reputation: 762
I think you need to know macro
and micro
tasks.
Microtasks
come solely from our code. They are usually created by promises: an execution of .then/catch/finally
handler becomes a microtask
If a microtask recursively queues other microtasks, it might take a long time until the next macrotask is processed. This means, you could end up with a blocked UI, or some finished I/O idling in your application.
example:
macrotasks
: setTimeout, setInterval, setImmediate, I/O, UI rendering, etc/
microtasks
: process.nextTick, Promises, etc.
code:
console.log('1')
setTimeout(()=>{
console.log('2')
},0)
Promise.resolve().then(()=>{
console.log('3')
})
console.log('4')
output:
1
4
3
2
wait what?!
explain:
console.log('1')
it's a normal code and immediately run.setTimeout
it's a macrotask then it will add to macro queuePromise.resolve
it's a microtask then it will add to micro queueconsole.log('4')
it a normal code and immediately run.now when normal codes are end and now microtaskqueue
and macrotaskqueue
need to be dequeue.
microtaskqueue
we have one task and it's Promise.resolve
then immediately run .then
functionnow microtaskqueue
is clear too, inside macrotaskqueue
we have one task and it's setTimeout
then immediately run timeoutCallback
function
if you want to use sleep
function without await
you need to handle this.
but you can add await
before your sleep
function and wait on it
Upvotes: 3