I have a queue of tasks that will run in Javascript, some are ajax calls, some are simple dom changes, so the time each one takes varies, but they need to run in order and wait their turn.
So for example, imagine this needs to happen:
Task 1: Takes 1s to complete
Task 2: Takes 0.5s to complete
Task 3: Takes 0.3s to complete
Task 4: Takes 0.75s to complete
Task 2 shouldn't run until task 1 is done (1s), etc.
I've tried using a foreach loop with a callback, but the faster tasks run before the slow ones, even if they are at the end of the queue. Here is a fiddle showing it in action.
https://jsfiddle.net/omp5cdm1/
var someArray = [1000, 500, 300, 750];
someArray.forEach(function(item, i) {
asyncFunc(item, function(item) {
console.log(i)
});
});
function asyncFunc( item, callback ) {
setTimeout(function() {
document.getElementById("output").innerHTML += item + ', ';
callback();
}, item);
}
Needed output: 1000, 500, 300, 750
<br>
<div id="output">Actual output:
</div>
Needed output order: 1000, 500, 300, 750
Actual output order: 300, 500, 750, 1000
Edit: I need to make it work on IE10+ too, so can't use es6 :(