Reputation: 2856
I have an array.
var a = [1,2,3,4,5,6,7,8,9,10];
for (var i = 0; i < a.length - 1; i++) {
console.log(a);
};
What do I need to do in order to create a timeout for this loop? Lets say I want to delay by 1 second.
Reason is because I want to http get() from a website and I don't want to flood them, however I want to make sure I get a response back prior to issuing my next response. However if a response comes back faster than 1 second I want to wait at least one second.
I have tried $interval, sometimes I get a response back from the server in 4 seconds and it issues more prior to the response coming back.
I am guessing I need promise prior to firing the next event? but a timer as well?
Please help.
Upvotes: 1
Views: 709
Reputation: 17269
Try $q.serial (a function not included by default in AngularJS) that is implemented and explained here.
var createTask = function (i) {
return function (delay) {
var start, end, nextRequestNeedsDelay;
var deferred = $q.defer();
if (delay) {
$timeout(function() {
start = Date.now();
$http.get("/foo")
.then(function () {
console.log(i);
end = Date.now();
nextRequestNeedsDelay = end - start < 1000;
deferred.resolve(nextRequestNeedsDelay);
});
}, 1);
} else {
start = Date.now();
$http.get("/foo")
.then(function () {
console.log(i);
end = Date.now();
nextRequestNeedsDelay = end - start < 1000;
deferred.resolve(nextRequestNeedsDelay);
});
}
return deferred.promise;
};
};
var a = [1,2,3,4,5,6,7,8,9,10];
var tasks = [];
for (var i = 0; i < a.length - 1; i++) {
tasks.push(createTask(i));
};
$q.serial(tasks);
Upvotes: 2
Reputation:
You can use the Promise Concept of angular. Promise provide the synchronous facility.
I demonstrate you to by giving the demo example
var app = angular.module("myApp",[ ]);
app.controller("ctrl",function($scope,$q,$timeout){
var task1 = $q.defer();
task1.promice.then(function(value){
// write a code here for your task 1 success
} ,function(value){
// write a code here for your task 1 error
});
var task2 = $q.defer();
task2.promice.then(function(value){
// write a code here for your task 2 success
} ,function(value){
// write a code here for your task 2 error
});
$q.all([task1.prpmice,task2.promice])
.then(function(){
// write a code which is executed when both the task are completed
} ,function(){
// write a code which is executed when some of the task are rejected
});
}
The above code will help you to understand the promice concept of angular
Upvotes: 1