简体   繁体   中英

setInterval loop doesn't wait at await

I made an example function 'webrequest()', imagine that this is a webrequest that takes 2 to get a response. I want to send a new webrequest after each response I receive. When I run te loop it just doesn't wait at the await and it sends another webrequest.

I have no idea what I did wrong. I can't find posts about this problem(maybe i'm searching wrong).

function webrequest() {
    return new Promise((resolve) => {
        setTimeout(()=>{
            resolve()
        },2000)
    })
}

function loopTest() {
setInterval(async () => {
    console.log('Welcome')
    await webrequest();
    console.log('Bye')
},10)
}

loopTest()

So the output should be.

Welcome
(2 seconds timeout)
Bye
Welcome
(2 seconds timeout)
Bye
...

There is no sense in using a short running setInterval then. Just use a loop:

  (async function() {
     while(true) {
       console.log('Welcome')
       await webrequest();
       console.log('Bye')
     }
})();

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:

It seems that it's setTimeout that fits the case. It should be isside promise in order to be used with async..await:

 function first(){ console.log('Welcome') } function second(){ console.log('Bye') } async function loopTest(){ await new Promise(resolve => setTimeout(() => resolve(first()), 1000)); await new Promise(resolve => setTimeout(() => resolve(second()), 1000)); } loopTest() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM