简体   繁体   中英

Callback after all functions done

This is just such a task, challenge, literally, everything that I have outlined is all information

We can add another argument for callback 'all is done'.

Important, console.log('all is done') need to be displayed only after all 'timer' functions have completed their execution, regardless of their call order.

I can't figure out which way to approach the task, I need to output using callback, but I need to wait for all calls to be completed What we have:

 //Write a “timer” function which takes a function and timeout, after all executions fire a callback ('all is done'): const timer = // your code timer( () => { console.log(500) }, 500 ) timer( () => { console.log(3000) }, 3000 ) timer( () => { console.log(1500) }, 1500 ) timer( () => { console.log(2500) }, 2500 )

If it is a promise related question, your constance returns a function with promise:

const timer = (timeout) =>  {
  return new Promise(function(resolve, reject) {
  setTimeout(function(timeout) {
    resolve(() => { console.log(timeout)});
  }, timeout);
});
}

Promise.all().then( () => { alert("All is done") })

This is how I solved the problem. It would be cool to solve it without using a global variable.

 //Write a “timer” function which takes a function and timeout, after all executions fire a callback ('all is done'): let maxTimer = 0; const timer = async (toRun, timeout) => { ++maxTimer const done = await new Promise((resolve, reject) => { setTimeout(() => { toRun() resolve() }, timeout) } ) if (maxTimer === 0){ console.log('all is done') } }// your code timer( () => { console.log(6000) --maxTimer }, 6000 ) timer( () => { console.log(500) --maxTimer }, 500 ) timer( () => { console.log(1500) --maxTimer }, 1500 ) timer( () => { console.log(7000) --maxTimer }, 7000 ) timer( () => { console.log(2500) --maxTimer }, 2500 )

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