Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  121] [ 2]  / answers: 1 / hits: 35960  / 11 Years ago, wed, january 8, 2014, 12:00:00

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.


More From » javascript

 Answers
16

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);
}
}

[#73311] Tuesday, January 7, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
miles

Total Points: 256
Total Questions: 111
Total Answers: 104

Location: Benin
Member since Fri, Mar 24, 2023
1 Year ago
;