简体   繁体   中英

Calling a setTimeOut after another setTimeOut in Pure JavaScript

I have two setTimeOut here. The second setTimeOut must be called after the first time out.

 setTimeout(() => { 
        mack.classList.add('loaded'); 
    }, 3000);

    setTimeout(() => { 
        location.reload(true);
    }, 4000);

But I know that this is not a good solution on this. So I tried to do a Promise:

  const timer = ms => new Promise(res => setTimeout(res, ms));

     Promise.all([
          timer(3000).then(mack.classList.add('loaded')),
          timer(1000).then(location.reload(true))
    ])

This however, did not work. How can I fix this to make it call in order? Also, is there a version to do this using asynchronous?

You are creating the promises, and then passing them to Promise.all , which waits for all of them simultaneously.

You want to start the second timer in response to the first timer.

This would do you you want:

timer(3000)
  .then(() => {
       mack.classList.add('loaded');
       return timer(1000);
  }).then(() => location.reload(true));

If you wanted this in an an async function:

async function example() {
   await timer(3000);
   mack.classList.add('loaded');
   await timer(1000);
   location.reload(true);
}

example().then(() => console.log('async function complete!'));

You are nearly there,

To use timer the way you want, you can use async / await , just remember to be able to use await , it has to be called withing another async function, here I've just placed inside an IFFE to achieve this..

 const timer = ms => new Promise(res => setTimeout(res, ms)); (async function () { console.log('Waiting 3 seconds'); await timer(3000); console.log('loaded'); await timer(1000); console.log('reload'); }());

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