Created
January 25, 2014 22:50
-
-
Save xdenser/8624867 to your computer and use it in GitHub Desktop.
SyncInterval
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
/** | |
* Created with JetBrains WebStorm. | |
* User: Den | |
* Date: 25.01.14 | |
* Time: 23:52 | |
* To change this template use File | Settings | File Templates. | |
*/ | |
var | |
timersArr = [], | |
cnt = 0; | |
function Timer(interval,callback){ | |
this.id = Date.now()+''+(cnt++); | |
this.interval = interval; | |
this.callback = callback; | |
timersArr.push(this); | |
if(timersArr.length==1) timer(); | |
} | |
function checkTimers(){ | |
var | |
i=timersArr.length, | |
ct = process.hrtime(), | |
ms = Math.floor(ct[1]/1000000), | |
ctm, ost; | |
while(i--){ | |
ctm = timersArr[i]; | |
ost = ms%ctm.interval; | |
if((!ost) && (ctm.last!=ms)) { | |
ctm.callback.call(this); | |
ctm.last = ms; | |
} | |
} | |
} | |
function timer(){ | |
checkTimers(); | |
if(timersArr.length) setImmediate(timer); | |
} | |
exports.setSyncInterval = function(callback,interval){ | |
var t = new Timer(interval,callback); | |
return t.id; | |
} | |
exports.clearSyncInterval = function(id){ | |
var idx; | |
timersArr.some(function(t,i){ | |
if(t.id==id){ | |
idx = i; | |
} | |
}); | |
if(idx>=0){ | |
timersArr.splice(idx,1); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment