-1

I have a multiple callback functions with own setTimeOut values. And when I try to run one after another sequentially the one with the shortest setTimeOut value is rendered first even when it's called the latest.

There are similar questions (like this, this and this), but their answers do not work when each function has own internal setTimeout value.

What would be the best way (using pure JS) to force the functions wait (or make sure the previous one finished running) until the previous one is finished, without using additional setTimeOut?

Code:

function NumSequences(){};

NumSequences.prototype.one = function one(callback) {
 setTimeout(function() {
   callback()
   console.log('one');
 }, 1000);
};

NumSequences.prototype.two = function two(callback) {
 setTimeout(function() {
   callback()
   console.log('two');
 }, 500);
};

NumSequences.prototype.three = function three(callback) {
 setTimeout(function() {
   callback()
   console.log('three');
 }, 200);
};
var numSequences = new NumSequences();

function countNow(){};

var promise = new Promise(function(resolve) {
   resolve(numSequences.one(countNow));
});

promise.then(function() {
  return numSequences.two(countNow);
}).then(function() {
  return numSequences.three(countNow); 
});

result:

three //coming first because the function three has the shortest setTimeout value
two 
one //coming at last despite being called first

And result should be:

one
two 
three

Link to JSBin

Amma
  • 177
  • 16

1 Answers1

0

You define functions for each portion of the procedure, use a copied array of arrays for parameters to function calls, shift the array until no elements remain in the array

function NumSequences(message, time) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve(message)
    }, time)
  })
}

function count(value) {
  console.log(value);
}

function next(array) {
  if (array.length) {
    return process(array)
  } else {
    return "done"
  }
}

let arr = [
  ["one", 1000],
  ["two", 500],
  ["three", 200]
];

let copy = arr.slice(0);

function process(array) {
  return NumSequences.apply(null, array.shift())
    .then(count)
    .then(next.bind(null, array))
}

process(copy)
.then(function(complete) {
  console.log(complete)
})
guest271314
  • 1
  • 15
  • 104
  • 177