Skip to content

Instantly share code, notes, and snippets.

@michalmikolajczyk
Created December 31, 2012 10:22
Show Gist options
  • Save michalmikolajczyk/4418802 to your computer and use it in GitHub Desktop.
Save michalmikolajczyk/4418802 to your computer and use it in GitHub Desktop.
The syncLoop() function creates a recursive, synchronous loop executed for each element of a given array and accepts callbacks. Example appliance: wait for user input before proceeding to the next element, without the need to execute the loop asynchronously (useful for dynamic code / metaprogramming) Notice that tail recursion isn't optimized in…
/*
* The syncLoop() function creates a synchronous loop
* that executes recursively for each element of a given array
* and accepts callbacks.
*
* I needed to wait for user input inside the loop and
* could not use process the elements asynchronously
* thus, here is the syncLoop()
*/
// Define the array to be iterated
var arr = ["my", "array"];
// Define the function to be executed on each element. The callback is used to iterate through the array
function insideTheLoop(arg1, callback) {
// your code
callback();
}
// Define the argument for insideLoop()
var arg1;
// Define callback to be executed after the syncLoop() ends
function loopCallback() {
// your code
}
// the syncLoop
function syncLoop(arr, i, loopCallback) {
if (i < arr.length) {
insideTheLoop(arg1, function() {
i++;
syncLoop(arr, i, loopCallback);
});
}
else {
loopCallback();
}
}
// Set the helper variable to 0
var i = 0;
// Call the function
syncLoop(arr, i, loopCallback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment