Last active
August 29, 2015 14:08
-
-
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"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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