Wait until the function is finished.

What is the best way to execute a function before the call ends?

JavaScript function example:

var notifyState = function(state) {
setTimeout(function () {
  /*Do something*/
}, 2000);
};

Then I call the function twice:

notifyState('State1');
notifyState('State2');

These functions are performed in parallel. What is the best way to execute them sequentially? I can only change the function notifyState. notifyStatecan only be performed with one parameter.

Update: The function notifyStatereports which actual state is in the flash game. It saves it in html code, when the state changes, then the state is redefined. In the selenium test, I load state from html code, but the state changes too quickly that selenium did not notice this, so I tried sleeping JavaScript.

+4
source share
3

, #notifyState setTimeout . setTimeout, :

var notifyState = function(state) {
  /* Do something */
}

notifyState('State 1');
notifyState('State 2');

setTimeout , , :

var notifyState = function(state, callback) {
  setTimeout(function() {
    /* Do something */
    if (callback) {
      callback();
    }
  }, 2000);
}

notifyState('State 1', function() {
  notifyState('State 2');
});

, . , #notifyState Flash, , , notifyState , 2 parallels StateState. , notifyState, . , setTimeout . . :

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

, . , , , .

var notifyState = function(state,fn) {
    setTimeout(function () {
      /*DoSomething*/
      if(typeof(fn)=='function'){ fn(); }
    }, 2000);
};

:

notifyState('State1', function(){
    notifyState('State2');
});

JSFiddle

+2
var notifyState = function(state, callback) {
    setTimeout(function () {

    /*Do something*/

    callback();

    }, 2000);
};

Call Function:

var state1CompleteHandler = function() {
    // code to execute when state 1 logic completes
    notifyState('State2');
}
notifyState('State1', state1CompleteHandler);
0
source

All Articles