Last active
December 17, 2015 23:39
-
-
Save v2keener/5690890 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* GIVEN: <div id='foo' /> such that out := $('#foo') | |
*/ | |
/* Enclosed code block (anonymous namespace) for execution */ | |
(function(){ | |
/* Wait times for window.setTimeout in seconds */ | |
var times = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.5,2.0]; | |
/* This is so that we have a stopping point to avoid infinite recursion | |
Because of the way this is designed, it could cause a browser to halt */ | |
var count = 1, maxCount = 1000; | |
/* The action that will be taken each time */ | |
var action = function(s){ | |
if(s){ | |
out.append("Waited " + s + " seconds<br />"); | |
} else { | |
out.append("Done!"); | |
} | |
}; | |
/* Build our queue FILO style ( displays "Done!" ) */ | |
var recursedTimeoutAction = function(){ action(); }; | |
/* Create a tail-recursive queue | |
(should be equiv to regular for loop)*/ | |
for(var i = times.length-1; i > -1; i--){ | |
var currentTime = times[i]; | |
/* Set global recursedTimeoutAction to itself | |
(in present state) executing current action */ | |
recursedTimeoutAction = (function(recursedCurrent, currentTime){ | |
/* Return a new function containing an execution against | |
the current value of recursedTimeoutAction as enclosed via | |
recursedCurrent */ | |
return function(){ | |
// Do not execute until we've passed currentTime seconds | |
window.setTimeout( | |
function(){ | |
// Display currentTime | |
action(currentTime); | |
/* NOTE: If we've gone to many times, break out. This is | |
handy if you edit this code and screw up, otherwise | |
you will halt your browser and possibly your computer | |
(stack overflow).*/ | |
if(count < maxCount){ | |
count++; | |
recursedCurrent(currentTime); | |
} else { | |
alert("ERROR: WENT THROUGH TOO MANY RECURSIONS" | |
+ " — Recursion limit = " + maxCount); | |
} | |
}, | |
currentTime*1000); | |
}; | |
}(recursedTimeoutAction, currentTime)); | |
} | |
/* Finally, call what we've built */ | |
recursedTimeoutAction(0); | |
}()); /* Execute this entire closure */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment