What is a best way to execute function until before call is finished?
Example JavaScript function:
var notifyState = function(state) {
setTimeout(function () {
/*Do something*/
}, 2000);
};
Then I call function twice:
notifyState('State1');
notifyState('State2');
This functions executing in paraller. What best way to execute them sequentially? I can only modify notifyState
function. notifyState
can execute only with one parameter.
Update:
Function notifyState
informs what actual state is in flash game. It saves it in html code, when state change then state is override. In selenium test I downloading state from html code, but state change too fast that selenium not noticed this, so I tried sleep JavaScript.
It depends on whether you want #notifyState to use setTimeout or not. If you don't need the setTimeout then you just re-write as follows:
var notifyState = function(state) {
/* Do something */
}
notifyState('State 1');
notifyState('State 2');
If you want to keep the setTimeout and chain the calls, so that the second notify is executed after the first, you will have to provide a callback:
var notifyState = function(state, callback) {
setTimeout(function() {
/* Do something */
if (callback) {
callback();
}
}, 2000);
}
notifyState('State 1', function() {
notifyState('State 2');
});
EDIT
Seems that the OP problem is different. My understanding is that your are providing #notifyState function as a callback to a 3rd party Flash that you don't control and you want to ensure that calls to notifyState execute in the same order and one after another, so you don't have 2 parallels calls to notifyState running at the same time. To achieve this you will need to introduce a queue that will keep the states and change the notifyState function in a way to execute only one state at the time. I will assume your need for the setTimeout is important here and keep it that way. See the code below:
var Queue = [],
running = false;
var notifyState = function(state) {
if (running) {
Queue.push(state);
} else {
running = true;
setTimeout(function() {
/* Do something */
running = false;
var nextState = Queue.pop();
if (nextState) {
notifyState(nextState);
}
}, 2000);
}
}
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