Created
February 1, 2012 22:05
-
-
Save ryan-blunden/1719765 to your computer and use it in GitHub Desktop.
Timing functions for Rhino
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
/** | |
* Timer for Rhino, original functions from http://stackoverflow.com/questions/2261705/how-to-run-a-javascript-function-asynchronously-without-using-settimeout#answer-5767884 | |
* written by Weston C. | |
* Packaged by Ryan Blunden | |
*/ | |
(function () { | |
var root = this, // global context | |
timer = new java.util.Timer(), | |
counter = 1, | |
ids = {}, | |
api = {}; | |
function setTimeout(fn,delay) { | |
var id = counter++; | |
ids[id] = new JavaAdapter(java.util.TimerTask,{run: fn}); | |
timer.schedule(ids[id],delay); | |
return id; | |
} | |
function clearTimeout(id) { | |
ids[id].cancel(); | |
timer.purge(); | |
delete ids[id]; | |
} | |
function setInterval(fn,delay) { | |
var id = counter++; | |
ids[id] = new JavaAdapter(java.util.TimerTask,{run: fn}); | |
timer.schedule(ids[id],delay,delay); | |
return id; | |
} | |
api = { | |
setTimeout: setTimeout, | |
clearTimeout: clearTimeout, | |
setInterval: setInterval, | |
clearInterval: setInterval | |
}; | |
// Export the timer object for **CommonJS**, with backwards-compatibility | |
// for the old `require()` API. If we're not in CommonJS, add `timer` to the | |
// global object. | |
if (typeof module !== 'undefined' && module.exports) { | |
module.exports = api ; | |
} else { | |
// Exported as a string, for Closure Compiler "advanced" mode. | |
root.timer = api; | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment