I have this code where I am using two javascript functions that do some manipulating for me. One function does some calculation but calls the other function before doing anything else. When the other function returns to it, it is supposed to do the final calculations.
The problem: The call to the other function is not executing properly. Even before the second function returns the first function executes completely.
code:
firstfunction{
secondfunction();
do something more nothing related to second
}
secondfunction(){
setTimeout(func1(){
do something independently
then call func1 depending on some condition
},time);
}
second function is used somewhere else also and is working fine.
My question:
I used this code thinking that the first function will not execute before second function executes completely. Is it right? Isn’t this the way javascript functions should run? The first function executes completely before second returns. I am sure of this because after second returns the position for the graphic first is supposed to place that graphic on screen. But the first executes completely and the graphic is placed awkwardly on screen and viewer can see it moving to right position given by the loop of second. Is setTimeout causing this problem?
Please help.
This happens because you use
setTimeout.setTimeoutwill make it asynchronous. Execution of second function will be completed after setting the interval and execution-flow will go back to first function. So you have to split your first function and make a third function which will have the final steps. This third function has to be invoked from thesetTimeouthandler.In this method you have to pass everything as parameters from one function to other.
You can also do this in a different way by making third one a callback function. This way you can make everything in the scope of firstfunction available for thirdfunction.