Created
November 11, 2011 23:44
-
-
Save rsbohn/1359687 to your computer and use it in GitHub Desktop.
Software watchdog in Javascript
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
// Use a watchdog to control functions that may take too long. | |
// You might use a watchdog to update the UI if your JSONP script fails to load | |
// in a timely manner. | |
function may_fail(n, slot) { | |
setTimeout(function(){ | |
//stop processing if the watchdog fired | |
if (dog[slot] == "FIRED") { | |
console.log("<may_fail slot='"+slot+"'> FAILED"); | |
return; | |
} | |
//we're ok so processing can continue | |
dog[slot]="SAFE"; | |
console.log("<may_fail slot='"+slot+"'> OK"); | |
//process http response or whatever | |
}, n); | |
} | |
var dog = {} | |
gscount=function(){ | |
var n = 0; | |
return function(){return n++} | |
}(); | |
function gensym(){return "sym"+gscount()} | |
function watchdog(func, time_allowed) { | |
var slot = gensym(); | |
dog[slot] = "ARMED"; | |
function watcher(captured) {return function() { | |
console.log(new Date()); | |
console.log(slot+" is "+dog[slot]); | |
if (dog[slot] == captured) { | |
console.log("***watchdog fired: bow-wow!"); | |
dog[slot]="FIRED"; | |
} | |
else {console.log("watchdog is sleeping.") } | |
}} | |
//Set the watcher to fire after the time_allowed | |
setTimeout(watcher(dog[slot]), time_allowed); | |
//Run the target function | |
func(slot); | |
} | |
console.log("Starting watchdogs..."); | |
//watchdog does not fire | |
watchdog(function(f){may_fail(100, f)}, 120); | |
//watchdog fires | |
watchdog(function(f){may_fail(200, f)}, 120); | |
watchdog(function(f){may_fail(300, f)}, 301); | |
watchdog(function(f){may_fail(320, f)}, 301); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment