Ever wanted to have a non-clamped setInterval
even in background tabs? Now you can! This works just like setInterval
and clearInterval
but in supported environments, uses a dynamically generated worker to run the timer, which avoids clamping in background tabs. No worries, if any of the necessary features to make this work are not supported, it will fall back to regular old setInterval
. :)
Created
January 6, 2012 21:32
-
-
Save devongovett/1572486 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
/* | |
* Non-clamped setInterval | |
* By Devon Govett (idea from sink.js) | |
* MIT LICENSE | |
*/ | |
(function() { | |
var BlobBuilder = this.BlobBuilder || this.MozBlobBuilder || this.WebKitBlobBuilder, | |
URL = this.URL || this.webkitURL, | |
Worker = this.Worker; | |
this.createTimer = function(fn, interval) { | |
if (!BlobBuilder || !URL || !Worker) | |
return setInterval(fn, interval); | |
var bb = new BlobBuilder; | |
bb.append("setInterval(function() { postMessage('ping'); }, " + interval + ");"); | |
var url = URL.createObjectURL(bb.getBlob()); | |
var worker = new Worker(url); | |
worker.onmessage = fn; | |
worker.url = url; | |
return worker; | |
} | |
this.destroyTimer = function(timer) { | |
if (timer.terminate) { | |
timer.terminate(); | |
URL.revokeObjectURL(timer.url); | |
} | |
else { | |
clearInterval(timer); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment