Jquery Daily Timer Failing
I am using this jQuery code to display the left left until 10am locally.
Between 10am and 14:00pm it removes some images.
Then after 14:00 it should display time left until 10am. It also add开发者_如何学JAVAs an offset to account for weekends.
It works brilliantly most of the time, however it seems after 14:00 it goes way over the time...
Can anyone see why this is failing, I've been looking at it for to long... now I'm just confussed! Please help!
$(document).ready(function() {
// 24 hour based
var targetTime = 1000;
var targetHour = 10;
var openingTime = 1400;
var openingHour = 14;
var currentTime = new Date();
// sun 0 mon 1 ... fri 5 sat 6
var currentDay = currentTime.getDay();
var offset = 24;
// friday
if (currentDay === 5) {
offset = 60;
} // saturday
else if (currentDay === 6) {
offset = 48;
}
var the_current_time = ''+ currentTime.getHours() + '' + currentTime.getMinutes() + '';
if( the_current_time > targetTime && the_current_time < openingTime ) {
var time_hours = (openingHour + offset) - currentTime.getHours() - 1;
var time_min = 60 - currentTime.getMinutes();
var time_seconds = 60 - currentTime.getSeconds();
$('#hours_left').append(time_hours, ':',time_min < 10 ? "0" : "" , time_min , ':' , time_seconds < 10 ? "0" : "" , time_seconds);
$('#watch_image').attr('src','http://cdn.shopify.com/s/files/1/0085/1702/t/1/assets/closed-until-icon.png');
$('#time-left-banner').css('width','275px');
$('.add-to-button').css('display','none');
$('#purchase').css('display','none');
}
else if( the_current_time > targetTime && the_current_time > openingTime ) {
var time_hours = (targetHour + offset) - currentTime.getHours() - 1;
var time_min = 60 - currentTime.getMinutes();
var time_seconds = 60 - currentTime.getSeconds();
$('#hours_left').append(time_hours, ':',time_min < 10 ? "0" : "" , time_min , ':' , time_seconds < 10 ? "0" : "" , time_seconds);
}
else {
var time_hours = (targetHour + offset) - currentTime.getHours() - 1;
var time_min = 60 - currentTime.getMinutes();
var time_seconds = 60 - currentTime.getSeconds();
$('#hours_left').append(time_hours, ':',time_min < 10 ? "0" : "" , time_min , ':' , time_seconds < 10 ? "0" : "" , time_seconds);
}
});
First, I would simplify the code a bit. The three var
calculation in all three branches seem to be the same. So is the updating of #hours_left
. You should be able to factor them out of the if
. This will also reduce the number of if branches from 3 to 1 - if I am not missing something.
As for the problem, I would look at the_current_time
. You are not zero padding the minutes, so 10:05 will become 105, or 1:05. I can't see how this would cause any dramas, as the calculations do not depend on this value, but it will change the if branch you will take.
Ah, I missed the time_hours
calculation difference in the first branch of if
. It uses opening_hours
instead of target_hours
. This explains why a bad the_current_time
will make a difference on the reported value.
精彩评论