function first(){ console.log('first') } function second(){ console.log('second') } let interval = async ()=>{ await setInterval(first,2000) await setInterval(second,2000) } interval();
Imagine that I have this code above.
When I run it, first()
and second()
will be called at the same time; how do I call second()
after first)()
returns some data, for example, if first()
is done, only then call second()
?
Because first()
in my code will be working with a big amount of data and if this 2 functions will be calling at the same time, it will be hard for the server.
How do I call second()
each time when first()
will return some data?
function first(){ console. log('first') } function second(){ console. log('second') } let interval = async ()=>{ await setInterval(first,2000) await setInterval(second,2000) } interval();
Even if you set a 0 delay, your code could be executed much later. setInterval has the same behavior as setTimeout but the code is executed multiple times. You have to call clearInterval to kill the timer. setTimeout and setInterval are the only native functions of the JavaScript to execute code asynchronously.
Nested setTimeout calls are a more flexible alternative to setInterval , allowing us to set the time between executions more precisely. Zero delay scheduling with setTimeout(func, 0) (the same as setTimeout(func) ) is used to schedule the call “as soon as possible, but after the current script is complete”.
Introduction to JavaScript setInterval() The setInterval() repeatedly calls a function with a fixed delay between each call. In this syntax: The callback is a callback function to be executed every delay milliseconds.
As mentioned above setInterval
does not play well with promises if you do not stop it. In case you clear the interval you can use it like:
async function waitUntil(condition) { return await new Promise(resolve => { const interval = setInterval(() => { if (condition) { resolve('foo'); clearInterval(interval); }; }, 1000); }); }
Later you can use it like
const bar = waitUntil(someConditionHere)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With