Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zlargon/06e8a5733c0973045d15 to your computer and use it in GitHub Desktop.
Save zlargon/06e8a5733c0973045d15 to your computer and use it in GitHub Desktop.
Show how to handle the asynchronous function in the for-loop. until all the function complete, then print out "all the tasks are completed"
var demo = function (num, callback) {
var counter = 0;
var checkTasksComplete = function() {
counter++;
if (counter === num) {
callback();
}
};
// Closure: create a new function with console.log(string)
var getFunction = function(n) {
var string = (n % 2 === 1 ? "odd " : "even ") + n;
return function() {
console.log(string);
// if all the tasks are completed, invoke the callback function
checkTasksComplete();
}
};
var getDelayTime = function(n) {
// odd delay 50, even delay 1000
return n % 2 === 1 ? 50 : 1000;
};
// start for-loop
for (var i = 0; i < num; i++) {
setTimeout(getFunction(i), getDelayTime(i));
}
};
// show the odd first, then show the even
demo(200, function() {
console.log("all the tasks are completed");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment