Skip to content

Instantly share code, notes, and snippets.

@matix
Created December 13, 2012 18:58
Show Gist options
  • Save matix/4278701 to your computer and use it in GitHub Desktop.
Save matix/4278701 to your computer and use it in GitHub Desktop.
desync() function utility. Desynchronize functions so they run after the current execution stack. Also provide a "timeout" to throttle the function. Throttle = avoid calling the function until certain time has passed, and reset that time everytime the function is called again, useful for performance improvements over very jumpy events.
function changeAllAnchorColor(color){
var anchors = document.body.getElementsByTagName("a");
for (var i = 0, l = anchors.length; i<l; i++){
anchors[i].style.color = color;
}
}
var changeAllAnchorColorDesynched = desync(changeAllAnchorColor);
document.body.innerHTML = "<div id=container><a href=#>LOL This code does nothing...</a></div>";
//We need to give innerHTML some time to parse the html string, in some browsers the contents will not be available right away on the next line.
changeAllAnchorColor("red"); //Will probably fail if parser is not fast enough
changeAllAnchorColorDesynched("red"); // Works everytime! :D
// some heavy load operation we need to be called on a certain event.
function resizeAllDivs(e) {
var divs = document.body.getElementsByTagName("div");
for (var i = 0, l = divs.length; i<l; i++){
var div = divs[i];
div.style.width = document.documentElement.clientWidth;
div.style.height = document.documentElement.clientHeight;
}
}
window.addEventListener("resize", resizeAllDivs); // Heavy load, will call on EVERY event dispatched.
var resizeAllDivsThrottled = desync(resizeAllDivs, 100);
window.addEventListener("resize", resizeAllDivsThrottled); // Will call only once every 100 ms at most. Controlled performance.
function desync (fn, timeout){
if(typeof fn === "function"){
timeout = (typeof timeout === "number")? timeout: 0;
return function(){
var self = this,
args = arguments;
if(fn.__desynced){
clearTimeout(fn.__desynced);
}
fn.__desynced = setTimeout(function(){
delete fn.__desynced;
fn.apply(self, args);
},timeout);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment