Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async await with setInterval

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?

like image 317
Andrey Radkevich Avatar asked Sep 05 '18 11:09

Andrey Radkevich


People also ask

How do I use async await in setInterval?

function first(){ console. log('first') } function second(){ console. log('second') } let interval = async ()=>{ await setInterval(first,2000) await setInterval(second,2000) } interval();

Does setInterval run async?

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.

What can I use instead of setInterval?

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”.

Is setInterval a callback function?

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.


1 Answers

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) 
like image 67
mdikici Avatar answered Sep 16 '22 14:09

mdikici