I have two asynchronous objects fn1 and fn2 and sometimes I want to run them synchronously.
For simplicity I wrote the code in this way:
var fn1 = function () {
setTimeout(function () {
console.log("fn1");
},200);
};
var fn2 = function () {
setTimeout(function () {
console.log("fn2");
},100);
};
fn1();
fn2();
but let's suppose is not possible to modify the fn1 and fn2 object.
What is the best way to run fn2 only when fn1 has finished to be executed?
If you want to execute f1() when f2() has finished, use the method as described and shown below.
Create a poller function, which checks for variable/property changes created by method fn2. Example:
function fn1(){/*...*/}
function fn2(){
//Lots of code, including:
window.someDynamicVar = "SPECIAL_token"; //Unique, only defined by this func
}
(function(){//Anonymous wrapper, don't leak variables
var timer = window.setInterval(function(){
//check whether an unique environment change has been made by fn2():
if(window.someDynamicvar == "SPECIAL_token"){
clearInterval(timer); //Clear the poller
fn1(); //Call fn1
}
}, 200); //Poller interval 200ms
})();
The concept behind this code is that the fn2() function changes variables during/after execution, which can be read. When such a change has been detected, the poller is cleared, and fn1() is executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With