I have countdown time for 15 seconds. It refreshes when 1 second on it. I also need refresh timer when user clicks at link on my website. I use cookie to provide no refreshing of timer when user refreshes page. Now when I click at link my timer refreshes but my old timer continues to countdown. As a result I have two timers and every second I see values from different timers. For example: I have countdown timer for 15 second. I click at link when value on timer was 7 seconds, and I see something like this: 15, 6, 14, 5, 13, 4, 12, 3 etc. But I need normal sequnce such 15, 14, 13 etc. What should I do for it? Below is my code:
// calls when I click at link
function rate(auct_id){
$.ajax({
type: 'POST',
url: '/auth/rate',
data: {'id': auct_id },
success: function(data) {
data = jQuery.parseJSON(data);
if (data.message) {
alert(data.message);
if (data.message != 'rates_count') {
windows.location = '/#openModal';
}
} else {
var new_price = data.price;
var new_login = data.login;
new_price += '<span> руб.</span>';
$('#price_' + auct_id).html(new_price);
$('#login_' + auct_id).html(new_login);
setTimer(auct_id, true);
}
}
});
}
function setTimer(id, update) {
var countdown4;
if(getCookie('countdown_' + id) && !update) countdown4 = getCookie('countdown_' + id);
else countdown4 = 15;
if (update) delete_cookie('countdown_' + id);
do_cd4(id, countdown4, update);
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
function convert_to_time(secs) {
secs = parseInt(secs);
hh = secs / 3600;
hh = parseInt(hh);
mmt = secs - (hh * 3600);
mm = mmt / 60;
mm = parseInt(mm);
ss = mmt - (mm * 60);
if (hh > 23) {
dd = hh / 24;
dd = parseInt(dd);
hh = hh - (dd * 24);
} else {
dd = 0;
}
if (ss < 10) {
ss = "0" + ss;
}
if (mm < 10) {
mm = "0" + mm;
}
if (hh < 10) {
hh = "0" + hh;
}
if (dd == 0) {
return (hh + ":" + mm + ":" + ss);
}
else {
if (dd > 1) {
return (dd + " day " + hh + ":" + mm + ":" + ss);
} else {
return (dd + " day " + hh + ":" + mm + ":" + ss);
}
}
}
// Our function that will do the actual countdown
do_cd4 = function(id, countdown4, update) {
//console.log(countdown4);
if (countdown4 < 1) {
countdown4 = 15;
do_cd4(id, countdown4);
} else {
$('#timer_' + id).html(convert_to_time(countdown4));
setTimeout(function() {
do_cd4(id, countdown4, update);
}, 1000);
}
setCookie('countdown_' + id, countdown4, 3);
countdown4 = countdown4 - 1;
}
The question has already been asked : Resetting a setTimeout
You need to keep a reference on your setTimeout, so you can clear it or restart it.
Related
var timeoutHandle;
function countdown(minutes,stat) {
var seconds = 60;
var mins = minutes;
if(getCookie("minutes")&&getCookie("seconds")&&stat)
{
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
}
function tick() {
var counter = document.getElementById("demo");
setCookie("minutes",mins,1);
setCookie("seconds",seconds,1);
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
//save the time in cookie
if(current_minutes.toString()== 30)
{
$("#myModal").modal();
}
if( seconds > 0 ) {
timeoutHandle=setTimeout(tick, 1000);
} else {
if(mins > 1){
/* countdown(mins-1); never reach “00″ issue solved:
Contributed by Victor Streithorst */
setTimeout(function () { countdown(parseInt(mins)-1,false); }, 1000);
}
}
}
tick();
}
function setCookie(cname,cvalue,exdays) {
if(exdays > 0)
{
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}else{
var expires="expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/;";
document.cookie = cname+"="+cvalue+"; "+expires;
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
countdown(60,true);
$("li a").click(function(){
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
$.cookie("minutes", null, { path: '/' });
$.cookie("seconds", null, { path: '/' });
});
I have two variables in above code. When I am trying to logout, both variables which are previously set in cookie, are not going to reset. Please let me know what I am doing wrong here. Thanks in advance.
You might want to remove the cookies those variables are reading from in your logout function:
try look at this: How to delete a cookie?
in particular :
function removeItem(sKey, sPath, sDomain) {
document.cookie = encodeURIComponent(sKey) +
"=; expires=Thu, 01 Jan 1970 00:00:00 GMT" +
(sDomain ? "; domain=" + sDomain : "") +
(sPath ? "; path=" + sPath : "");
}
removeItem("cookieName");
I am making a simple time calculator in javascript. I have converted the times into 12-hour instead of 24 hour time for simplicity, however the code I have for calculating am/pm always shows am. Any reason why this would be happening?
Here is my code:
function solveTime(x) {
var suffixSolve = (utcHours + x) % 24;
var suffix = "am";
if (utcHours > 12) {
var suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
and here is the code behind utcHours
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
Example here: http://codepen.io/markgamb/pen/gwGkbo
The issue is you should be checking whether suffixSolve is greater than 12 instead of utcHours, because utcHours does not change due to the value of x. Since you can shift the hours forward and backwards, I created a variable shift to handle that.
function solveTime(x) {
if (x < 0) {
var shift = 24 + x;
} else {
var shift = x;
}
var suffixSolve = (utcHours + shift) % 24;
var suffix = "am";
if (suffixSolve > 12) {
suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
solveTime(4);
solveTime(0);
solveTime(-8);
<div id="4"></div>
<div id="-8"></div>
<div id="0"></div>
I'm having a problem with a count down timer made in JavaScript. It was working for the last 2 weeks, but today it started to show NaN:NaN... , and I can't understand why. Here is the code, does anyone have any idea which one could be the problem?
<div id="countdownmain">
<span id="countdownmain" class="timer"></span>
</div>
<script>
var date = new Date;
var secondsnow = date.getSeconds();
var minutesnow = date.getMinutes();
var hournow = date.getHours();
var day = date.getDay();
var passatti = (secondsnow + (minutesnow*60) + (hournow*3600));
if((day==1)||(day==2)||(day==3)||(day==4)){
if(passatti < 46800){
var upgradeTime = 46800 - passatti;
}else if(passatti > 46800){
var upgradeTime = 86400 - passatti + 46800;
}
}else if((day==5)&&(passatti < 46800)){
var upgradeTime = 46800 - passatti;
}else if((day==5)&&(passatti > 46800)){
var upgradeTime = 86400 - passatti + 46800 + 86400 + 86400;
}else if((day==6)){
var upgradeTime = 86400 - passatti + 46800 + 86400;
}else if((day==7)){
var upgradeTime = 86400 - passatti + 46800;
}
var seconds = upgradeTime;
function timer() {
var now = Math.floor(Date.now() / 1000);
('0' + 11).slice(-2)
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdownmain').innerHTML = "<span class='timesm'> For same working day dispatch, order in </span><br class='appear'><span style='display:inline-block; width:45px;'><span class='hideDays glowW'>" + ('0' + days).slice(-2) + "</span></span><span class='times'> days </span><span style='display:inline-block; width:45px;'><span class='hideHours glowW'>" + ('0' + hours).slice(-2) + "</span></span><span class='times'> hours </span><span style='display:inline-block; width:45px;'><span class='hideMinutes glowW'>" + ('0' + minutes).slice(-2) + "</span></span><span class='times'> minutes </span><span style='display:inline-block; width:45px;'><span class='hideSec glowW'>" + ('0' + remainingSeconds).slice(-2) + "</span></span><span class='times'> seconds </span>";
if (seconds == 0) {
clearInterval(countdownTimer);
//document.getElementById('countdownmain').innerHTML = "Completed";
seconds = upgradeTime;
} else {
seconds--;
$('.hideSec').fadeOut('slow');
}
if(('0' + remainingSeconds).slice(-2)==00){
$('.hideMinutes').fadeOut('slow');
}
if((('0' + minutes).slice(-2)==00)&&(('0' + remainingSeconds).slice(-2)==00)){
$('.hideHours').fadeOut('slow');
}
if((('0' + hours).slice(-2)==00)&&(('0' + minutes).slice(-2)==00)&&(('0' + remainingSeconds).slice(-2)==00)){
$('.hideDays').fadeOut('slow');
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
Unfortunately, today is Sunday! Javascript return 0 value as first of a week in getDay().
Take a look my fiddle. I just decreased day comparator value in if statement. (e.g. 1 -> 0, 2 -> 1, 3 -> 2 and so on..)
I have developed a JSP page. On this page, I have a count-down timer that displays time in hh:mm:ss. A link is provided to the previous page (page 2) from this page. After some work on page 2, control will be transferred to page 1 again.
I have a timer that starts when page 1 loads. When I go to page 2 and return to page 1, the timer gets refreshed. How can I make it start from where it was when I left the page?
Here's my timer code:
<script language="JavaScript">
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;
function twoDigits( n ) {
return (n <= 9 ? "0" + n : n);
}
function getCurrentTime() {
time = new Date();
hours = time.getUTCHours();
mins = time.getUTCMinutes();
secs = time.getUTCSeconds();
alert(hours + " " + mins + " " + secs);
}
function updateTimer() {
msLeft = endTime - (+new Date);
if ( msLeft < 999 ) {
alert("please save your work and send your file!");
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
secs = time.getUTCSeconds();
element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits(secs);
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
if( hours == 0 && mins == 0 && secs == 59 ) alert("dsdsdsdsdsd");
}
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function getCookie ( name ) {
var cname = name + "=";
var dc = document.cookie;
if ( dc.length > 0 ) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
var exp = new Date();
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}
</script>
I think you can use cookies to store the current time and one flag=true before you switch to page 2; when you come back to page 1 you de-active flag=false to continue to calculate the time.
you can do follow steps below:
1) create a js file with content:
function setCookie(key, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = key + "=" + value + expires + "; path=/";
}
function getCookie(key) {
var nameEQ = key + "=";
var ca = document.cookie.split(';');
for ( var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function removeCookie(key) {
setCookie(key, "", -1);
}
2) At form 1 before click to go to form 2, you can set the current time to cookie.
setCookie("tracking_time", time_string, 5);
Please refer Javascript Date Time functions to know how to get/set a time string
3) when come back to form 1 from form 2, you can get time value from cookie , then you set to timer to continue count time.
var time_string = getCookie("tracking_time");
Then you parse time_string to object
This is a sample complete code
<html>
<head>
</head>
<body>
<span id="countdown">Start</span>
<script>
function setCookie(key, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = key + "=" + value + expires + "; path=/";
}
function getCookie(key) {
var nameEQ = key + "=";
var ca = document.cookie.split(';');
for ( var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function removeCookie(key) {
setCookie(key, "", -1);
}
var countdown = document.getElementById("countdown");
var days, hours, minutes, seconds;
var target_date = getCookie("tracking_time");
if (target_date == null) {
target_date = new Date().getTime() + (2*60*60*1000); // set countdown 2 hours
}
function updateTimer() {
setInterval(function () {
// this line below will set to function that user click on link to go to form 2
setCookie("tracking_time", target_date, 1);
// End line
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value
countdown.innerHTML = hours + "h: " + minutes + "m: " + seconds + "s";
}, 1000);
}
updateTimer();
</script>
</body>
</html>
I ran into a snag in my code, the code below is for a JavaScript clock which works perfectly:
function renderTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if(h == 0) {
h = 12;
} else if(h > 12) {
h = h - 12;
diem = "PM";
}
if(h < 10) {
h = "0" + h;
}
if(m < 10) {
m = "0" + m;
}
if(s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent = h + ":" + m + ":" + s + " " + diem;
myClock.innerHTML = h + ":" + m + ":" + s + " " + diem;
myClock.innerText = h + ":" + m + ":" + s + " " + diem;
setTimeout('renderTime()',1000);
}
renderTime();
However I am trying to do it slightly different now like this:
function makeTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if(h == 0) {
h = 12;
} else if(h > 12) {
h = h - 12;
diem = "PM";
}
if(h < 10) {
h = "0" + h;
}
if(m < 10) {
m = "0" + m;
}
if(s < 10) {
s = "0" + s;
}
var clock = document.getElementById('clock');
clock.innerHTML = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
myClock.textContent = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
myClock.innerText = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
setTimeout('makeTime()',1000);
}
makeTime();
This one works, however does not update like the other one, you have to manually refresh the page.
What am I doing wrong?
You continue to refer to myClock in your second version, when you've renamed the variable to clock:
var clock = ...
clock.innerHtml = ...
myClock.textContent = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
myClock.innerText = "<h1>"+h+":"+m+":"+s+":"+diem+"</h1>";
setTimeout('makeTime()',1000);
This is causing errors (reference error: myClock is not defined) which is preventing the flow of execution from reaching your setTimeout call.
You should learn to use the tools available to you. Every browser has a method of reporting JavaScript errors to developers. Open the developer console in Webkit/IE10, or Firebug in Firefox, you'll see these errors and exactly where they're happening in your code.