I am having trouble with Javascript async call. The Car class below has a move function which takes two arguments, the first one is a value, the second one is a call back function, which will be called after 1 second, and this callback function takes the value returned by forward method.
var Car = function() {
this._count = 0;
};
Car.prototype = {
move: function(value, onMoved) {
setTimeout(function() {
onMoved(this.forward(value));
}.bind(this), 1000);
},
forward: function(value) {
this._count = this._count + value;
return this._count;
}
};
I want to call the move function like this:
var values = [1, 2, 3, 4];
var car = new Car();
values.forEach(function(value) {
car.move(value, function(result) {
console.log(result);
});
});
Now my problem is the call back function onMoved does not wait for 1 second to execute between each value that it is outputting. How can I make it so it wait between each value that it is outputting? I am allowed to use underscore.js. Thanks.