I have a simple JS code to do countdown on the Client browser but there is a short coming the timer depends on the client machine so i want to get the Current Time and elapsed time from the Server.
Below is my working but it doesn't work.
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(current_time);
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime, current_time) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime, current_time);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
$('#clockdiv').html('You can\'t Reserve anymore')
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = '2017-02-24 18:12:29';
var current_time = new EventSource('Server/script/example.php');
current_time.onopen = function(event) {
//console.log(event)
current_time.onmessage = function(event)
{
return event.data;
}
current_time.onerror = function (error) {
//console.log('we have an error')
}
}
console.log(current_time)
initializeClock('clockdiv', deadline, current_time);
So am trying to use HTML SSE server Sent Event so as Listen to response instead of making the request.
current_time variable is empty and the output of the Time is NAN NAN NAN
So is there a better of achieving the above or can some work this code for me.