Skip to content

Instantly share code, notes, and snippets.

@etoxin
Last active August 29, 2015 14:07
Show Gist options
  • Save etoxin/060e3849e696b228e448 to your computer and use it in GitHub Desktop.
Save etoxin/060e3849e696b228e448 to your computer and use it in GitHub Desktop.
Asynchronous Callbacks
function logItem(item) {
console.log(item);
}
function asyncEach3(arr, callback) {
// Utility inner function to create a wrapper function for the callback
function makeCallbackWrapper(arr, i, callback) {
// Create our function scope for use inside the loop
return function() {
callback(arr[i]);
}
}
for (var i = 0; i < arr.length; ++i) {
setTimeout(makeCallbackWrapper(arr, i, callback), 0);
}
}
console.log("begin");
asyncEach3([1, 2, 3], logItem);
console.log("end");
function logItem(item) {
console.log(item);
}
function asyncEach3(arr, callback) {
// Utility inner function to create a wrapper function for the callback
function makeCallbackWrapper(arr, i, callback) {
// Create our function scope for use inside the loop
return function() {
callback(arr[i]);
}
}
for (var i = 0; i < arr.length; ++i) {
setTimeout(makeCallbackWrapper(arr, i, callback), 0);
}
}
console.log("begin");
asyncEach3([1, 2, 3], logItem);
console.log("end");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment