Skip to content

Instantly share code, notes, and snippets.

@rtfpessoa
Last active March 20, 2016 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtfpessoa/3a4d4047028d3cf22b2f to your computer and use it in GitHub Desktop.
Save rtfpessoa/3a4d4047028d3cf22b2f to your computer and use it in GitHub Desktop.
Two Factor Timer
var updateTimer = function(period, updateTokenCallback) {
// Get current time seconds
var epocSecs = Math.floor((+new Date()) / 1000);
var sec = epocSecs % period;
var secsToNext = 0;
// Fire if clock has struck 0 or 'period'
if (sec == 0 || sec == period) {
updateTokenCallback();
} else {
// If less than 'period', next update is at 'period'
if (sec < period) {
secsToNext = period - sec;
} else if (sec > period) {
secsToNext = period - sec;
}
}
return secsToNext;
};
var myTimer = function() {
var secsToNext = updateTimer(30, function() { console.log("Updating token...") });
console.log("Your token expires in: " + secsToNext);
};
setInterval(myTimer, 500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment