Created
June 28, 2009 16:15
-
-
Save furf/137303 to your computer and use it in GitHub Desktop.
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
/** | |
* Returns a unique GMT timestamp at every specified interval. | |
* | |
* Examples: | |
* <ul> | |
* <!-- Returns a unique timestamp every 10 minutes --> | |
* <li>var t10m = modTimestamp(600);</li> | |
* <!-- Returns a unique timestamp every 30 seconds --> | |
* <li>var t30s = modTimestamp('30');</li> | |
* </ul> | |
* | |
* Example usage: This function could be used to generate a pseudo-TTL in | |
* situations where server-side caching is not possible. Timestamp should | |
* be appended to each pseudo-cached file request. | |
* | |
* Examples: | |
* <ul> | |
* <li>var url = 'path/to/file/?' + modTimestamp(60);</li> | |
* <li>var url = 'path/to/file/?ts=' + modTimestamp(60);</li> | |
* </ul> | |
* | |
* @function | |
* @public | |
* @param {Number|String} interval Time in seconds between unique timestamps | |
* @throws {TypeError} interval must be a valid number | |
* @throws {Error} interval must be at least one second | |
* @returns {Number} Unique GMT timestamp | |
* @author David Furfero furf@furf.com | |
*/ | |
var modTimestamp = function(interval) { | |
if (isNaN(interval)) { | |
throw new TypeError('interval must be a valid number'); | |
} | |
if (interval < 1) { | |
throw new Error('interval must be at least one second'); | |
} | |
var now = new Date(), | |
tzOffset = now.getTimezoneOffset() * 60 * 1000, | |
gmt = (new Date(now.getTime() + tzOffset)).getTime(), | |
mod = parseInt(interval, 10) * 1000, | |
ts = gmt - gmt % mod; | |
return ts; | |
}; | |
var t10m = modTimestamp(600); // Returns a unique timestamp every 10m | |
var t30s = modTimestamp('30'); // Returns a unique timestamp every 30s | |
console.log(t10m); | |
console.log(t30s); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment