jQuery Countdown - reset timer

前提是你 提交于 2019-12-13 04:03:47

问题


I'm using the jQuery Countdown plugin and have a quick query.

My code currently looks like this:

function doCountdown(){
    var nextNoon = new Date();
    if (nextNoon.getHours()>=12){ nextNoon.setDate(nextNoon.getDate()+1); }
    nextNoon.setHours(11,30,0,0);

    $('h3 .timer strong').countdown({until: nextNoon, compact: true, 
        description: '',  onExpiry: function(){doCountdown()}});
}

$(window).load(function(){
     doCountdown();
});

So basically, it counts down untill the next 11:30AM. However I need it to reset the counter when it reaches 11:30AM, so it will automatically go to 23:59:59 on the timer.

Currently it just sticks at 00:00:00 even though the doCountdown function is called onExpiry (tested with console.log and it definitely calls it).

Is it because javascript bases the time off page load and then stores it?


回答1:


The reason is because your nextNoon creation miscalculates for times between 11:30am and 12:00pm. For that half an hour period, the if() will evaluate to false, so it will set the time as 11:30am of the current day. However we've already passed that time, since we're between 11:30am and 12noon. So the countdown will just go to zero.

You need to do as follows:

var todaysNoon = new Date(), nextNoon = new Date();
todaysNoon.setHours(11,30,0,0);
if (todaysNoon <= nextNoon){ nextNoon.setDate(nextNoon.getDate()+1); }
nextNoon.setHours(11,30,0,0);


来源:https://stackoverflow.com/questions/7686188/jquery-countdown-reset-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!