I am constructing a little app in javascript right now but I've clashed into a serious problem.
I am using at least 3 functions with timers on them (the 1st two running endlessly) and both of them use some global variables (in this case they are needed to be globa开发者_开发问答l because of some functions). The external functions external to those 3 don't have timers. One of the timer functions only activates when a certain action is taken, affecting the second function (right now I disabled it qith a flag). Still, when this timer function ends the other one is still running, trying to get some incoherent data (trying to get to negative indexes on a matrix to be precise) and crashing (the flag is switched but the main data isn't fixed yet -> like a multi-threading problem).
What I want to ask is, there is any way to make a function "wait" for another to end in javascript? Or any other way or coordinating those functions between them (in mutex style or sort of)?
Javascript is single threaded, so it's going to be nearly impossible to come up with any sort of "multi-threading" type solution. I would try to come up with some way to use a single function and one timer, and handle the different pieces of logic with flags. For example, maybe you could do one piece of the logic if flag A is set, then set flag B. When the timer fires again, you could do the flag B logic (using this same function).
On a more positive note, it does seems that HTML5 will support multithreading, which is encouraging, but it doesn't really address the problem at hand.
Javascript is actually single threaded, except that timers execute asynchronously.
If this is running in a browser then I strongly recommend using jQuery's new "deferred" objects, or any other framework that implements something similar.
These allow you to trigger another callback only when all of a set of asynchronous events have completed, which may be just what you need.
精彩评论