Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until function is finished

Tags:

javascript

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.

like image 315
estradowiec Avatar asked Feb 14 '23 04:02

estradowiec


1 Answers

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);
  }
}
like image 180
edzhelyov Avatar answered Feb 17 '23 03:02

edzhelyov