user329072 user329072 - 6 months ago 87
jQuery Question

JavaScript Countdown Timer to specific time everyday

I am currently developing a website with a countdown timer at the headline: http://iphone.myhandykey.com/

The current timer is just 12hrs + few mins.. What I would like is the countdown timer will show the time remaining until 11PM on the Time Zone of the current visitor. Is that possible? Thanks!

Here is the JavaScript:



function startTimer(duration, display) {
var timer = duration, hours, minutes, seconds;
setInterval(function () {



hours = parseInt(((timer / 60) / 60 ) % 60, 10);



minutes = parseInt((timer / 60)%60, 10);
seconds = parseInt(timer % 60, 10);

hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;

display.textContent = hours + ":" + minutes + ":" + seconds;



if (--timer < 0) {
timer = duration;
}
}, 1000);
}

window.onload = function () {
var onehour = 60 * 600 * 1.231,
display = document.querySelector('#time');
startTimer(onehour, display);
};


Here is the HTML:

<span id=time></span>


EDIT: If the visitor's current time is for example 11:40pm, It should display 23hrs & 20mins left..

Answer

(function() {
  var start = new Date;
  start.setHours(23, 0, 0); // 11pm

  function pad(num) {
    return ("0" + parseInt(num)).substr(-2);
  }

  function tick() {
    var now = new Date;
    if (now > start) { // too late, go to tomorrow
      start.setDate(start.getDate() + 1);
    }
    var remain = ((start - now) / 1000);
    var hh = pad((remain / 60 / 60) % 60);
    var mm = pad((remain / 60) % 60);
    var ss = pad(remain % 60);
    document.getElementById('time').innerHTML =
      hh + ":" + mm + ":" + ss;
    setTimeout(tick, 1000);
  }

  document.addEventListener('DOMContentLoaded', tick);
})();
Only <span id='time'></span> left!