JavaScript count down, add hours & minutes

前端 未结 3 2001
无人共我
无人共我 2021-02-11 04:03

So, I have the below (seconds countdown) in good order. But! I am trying to add hours & minutes as apart of the count down as well. Ideally keeping the same structure, and j

3条回答
  •  醉酒成梦
    2021-02-11 04:27

    I would use a similar method to the others, but I wouldn't rely on setInterval / setTimeout as a timer, especially if users might be looking at the page for some time, as it tends to be inaccurate.

    var endTime = new Date(2013, 10, 31).getTime() / 1000;
    function setClock() {
        var elapsed = new Date().getTime() / 1000;
        var totalSec =  endTime - elapsed;
        var d = parseInt( totalSec / 86400 );
        var h = parseInt( totalSec / 3600 ) % 24;
        var m = parseInt( totalSec / 60 ) % 60;
        var s = parseInt(totalSec % 60, 10);
        var result = d+ " days, " + h + " hours, " + m + " minutes and " + s + " seconds to go!";
        document.getElementById('timeRemaining').innerHTML = result;
        setTimeout(setClock, 1000);
    }
    setClock();
    

    This method calculates the difference between now and the date in the future each time it is run, thus removing any inaccuracies.

    Here is an example: http://jsfiddle.net/t6wUN/1/

提交回复
热议问题