Call a function when other async functions have finished, pure javascript

Assuming you have a <div id=”x”> or just output to the console

/* This demonstrates how to call a function when two other async functions, f1 and f2, have finished.
f1 and f2 use setTimeout, which is async, meaning the rest of the code will run immediatly after being called, and a callback function will be called when setTimeout has finished.
setTimeout has to be understood as calls to API server functions that can take some time to execute
*/
var req1, req2 = false // flags to know when functions are done. It can very well be a counter if there are many and you don't need to know which function has finished.
x.innerHTML= "waiting for f1 and f2 to end in order to call f3...<br>"
// f1 and f2 are called at the same time
f1();
f2();

function f1(){
x.innerHTML = x.innerHTML + "f1 called...<br>"
setTimeout(function afterThreeSeconds() {
	req1=true;
  x.innerHTML = x.innerHTML + "f1 finished. <br>"
  if (req1&&req2){f3()}
}, 3000)}

function f2(){
x.innerHTML = x.innerHTML + "f2 called...<br>"
setTimeout(function afterTwoSeconds() {
	req2=true
    x.innerHTML = x.innerHTML + "f2 finished. <br>"
  if (req1&&req2){f3()}
}, 2000)}

// f3 will be called immediately after both f1 and f2 are done
function f3(){
	x.innerHTML = x.innerHTML + "f3 called because f1 & f2 finished :)"
}

 

Published by

Nelson Muskus

Full Stack developer

Leave a Reply

Your email address will not be published.