1

How do i make countdown timer that will be the same for everyone regardless their time on pc. The script doesn't work as i wanted it to, basically anyone can change the timer with just changing date and time on their pc.

var end = new Date('07/31/2015 4:10 pm');

var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;

function showRemaining() {
    var now = new Date();
    var distance = end - now;
    if (distance < 0) {

        clearInterval(timer);
        document.getElementById('giveaway1').innerHTML = 'The Winner Has Been Chosen!';

        return;
    }
    var days = Math.floor(distance / _day);
    var hours = Math.floor((distance % _day) / _hour);
    var minutes = Math.floor((distance % _hour) / _minute);
    var seconds = Math.floor((distance % _minute) / _second);

    document.getElementById('giveaway1').innerHTML = days + 'days ';
    document.getElementById('giveaway1').innerHTML += hours + 'hrs ';
    document.getElementById('giveaway1').innerHTML += minutes + 'mins ';
    document.getElementById('giveaway1').innerHTML += seconds + 'secs';
}

timer = setInterval(showRemaining, 1000);

2
  • Basically you don't need to use the time base on their pc time/date. You will use the time/date of your server time where you hosted your code. Commented Jul 30, 2015 at 10:29
  • Why don't you just set the variable "now" outside the function and add 1000 seconds to it every showRemaining()? That way your users will have to change the date before the script starts. Commented Jul 30, 2015 at 10:31

1 Answer 1

3

Since local PC time is outside your control, you will have to get the reliable time from your server (or a third-party server) at least once.

Once you know what the (correct) server time is, you can subtract server time from local PC time to get the 'offset' (i.e. the difference between server time and local PC time).

Once you have that offset you can then at any time get the local PC time - via new Date() - and factor in the offset to get the 'correct' server time, without having to call the server each time.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice mambo, good explanation. I'm just typing and you already answered :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.