Plain javascript plugin to sync client time with server time
Basic usage:
var timekeeper = TimeKeeper({
ajaxType: 'get',
ajaxMilliUrl: '/utcMillis',
responseParser: function (response) {
return parseInt(response);
},
});
timekeeper.sync(function () {
console.log('Correct date:', timekeeper.Date());
});
NOTE: responseParser
must return date in milliseconds
Sync at regular interval:
var timekeeper = TimeKeeper();
timekeeper.on('synced', function () {
console.log('Synced successfully');
});
timekeeper.startSync(5 * 60 * 1000); // Will sync regularly at 5 min interval
Or if you already know the current correct time:
var timekeeper = TimeKeeper({ correctTimeInMillis: 1467451864591 });
console.log('Correct time:', timekeeper.Date());
/**
* Or you can use "setCorrectTimeInMillis" method
*/
var timekeeper = TimeKeeper();
timekeeper.setCorrectTimeInMillis(1467451864591);
console.log('Correct time:', timekeeper.Date());
You can also override native Date
with correct Date
:
var timekeeper = TimeKeeper({ overrideDate: true, correctTimeInMillis: 1467451864591 });
console.log('Correct time:', new Date());
correctTimeInMillis
- Correct time (server time)ajaxType
- HTTP Method type [get
/post
/put
]ajaxMilliUrl
- URL to hit to fetch time in UTC milliseconds (Default value: "/utcMillis")syncInterval
- Interval at which sycn should happenresponseParser
- Parser method for responsedifferenceInMillis
- Incase you know difference of machine time and server time in milliseconds you can pass
sync
- Fetches server timeDate
- Gets Date object with server time (correct time)startSync(<intervalInMilliseonds>)
- Starts to run sync operation at given regualar intervalstopSync
- Stops sync operation loopsetCorrectTimeInMillis((<timeInMillis>))
- Sets correct time (server time)overrideDate
- Overrides default Date object with server time Date objectreleaseDate
- UndosoverrideDate
operationsetDifferenceInMillis(<timeInMillis>)
- Sets the server and client time differencegetDifferenceInMillis
- Gets the server and client time differenceon(<eventName>, <eventHandlerMethod>)
- Attaches eventsoff
- Removes events
- Supported events
sync
- Will be triggered before syncing (prehook for sync)synced
- Will be triggered when time sync is successfulsync_error
- Will be triggered when time sync failsfirst_sync
- Will be triggered before syncing for the first timefirst_synced
- Will be triggered when time sync for first time is successfulfirst_sync_error
- Will be triggered when time sync for first time fails
Have you seen chat application showing "1 day ago" for a message which you received just now.
This is probably because the client machine time is set wrongly.
To avoid this chaos the client time should be in sync with server time.
- Clone the project
git clone https://github.com/Sujsun/timekeeper.git
- Install npm dependencies
npm install
-
Run the server
npm start
orgrunt
-
Visit
http://localhost:8989
orhttp://127.0.0.1:8989