I want to detect the end of an async function inside the for loop in JavaScript.
My code is:
for (var i = 0; i < dataPoints.length; i++) {
(function(i) {
setTimeout(function() {
if(end of everything)
{
//call xyz()
}
}, 5000 * i);
})(i);
}
Please help me in achieving my target. Thanks
You can just check if i
is the last index of the array:
dataPoints = [1, 2, 3];
for (var i = 0; i < dataPoints.length; i++) {
(function(i) {
setTimeout(function() {
console.log(i);
if(i === dataPoints.length - 1) // if i is the last iteration
{
console.log('the end');
//call xyz()
}
}, 1000 * i); // changed 5s to 1s for demo
})(i);
}