how to create a javascript countdown which on refreshing continues counting - javascript

I try it with javascript and jquery but no idea how to do that. i wont to let the timer not begins on refreshing counting again. It´s same as an auction when he counting down 3,2 and on refreshing he don´t begins again it should continue count down where it last ended. And on other products it must count from 3 again. Have anyboy an idea?
Edit: because some users missunderstood what i am searching for.
my issue is that i don´t know how to save the time when someone refresh the page to continue to count it down. if someone refresh the site at 21sec and he or she have 30 secs to make there choice. and after refreshing the site, the counter will count at 21sec down and not started again by 30sec again.
no ajax.
When possible hardcoded.
And if not possible then the cookie variant.

You can set a name to your window on load of the page. Before setting the name check whether this window already has a name.
if it doesn't have a name, set a name to the window and start counting at 0 and save the count value in a cookie each time it increment.
if it does have a name(that means page is reloaded), read the count value from the cookie and do the increment and save to cookie.
EDIT: Example, Call initCount() function on body load. Use decrementAndSave function to decrement the value of the count and save it to cookie.
var count = 3;// 3 -> 2 -> 1
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;
}
function initCount() {
if (window.name) {
count = getCookie("count_" + window.name);// to keep separate count cookies for each window
} else {
window.name = "w_" + (new Date().getTime());
count = 3;
setCookie("count_" + window.name, count, null);
}
}
function decrementAndSave() {
count--;
// separate cookie for each window or tab
setCookie("count_" + window.name, count, null);
}

It's not Perfect but I designed this script to do a 30min countdown and then to change some text during the last few seconds. The only issue with it is that when it gets to 1:00 it starts at 30:60 and I haven't figured out how to fix that yet. This may not work perfectly for what your looking for but it might put you on the right path.
<script>
//add leading zeros
setInterval(function() {
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var x = document.getElementById("timer");
var d = new Date();
var s = (d.getSeconds());
var m = (d.getMinutes());
var a = addZero(30 - m);
var b = addZero(60 - m);
var c = (60 - s);
var z = "<span style='color:red;font-size:50px;'>" + "Break" + "</span>";
var v = "<span style='color:black;font-size:24px;'>" + "Break" + "</span>";
//Decide how much should be subtracted from the time
if (m > 30) {
y = b;
}
else if (m < 30) {
y = a;
}
//elements for changing text
if (y < 2 && c < 15) {
q = z;
}
else {
q = v;
}
var t = y + (":" + addZero(c) + " Till Station " + (q));
x.innerHTML = t;
}, 250);
</script>
<div align="center" id="timer" style='color:black;font-size:24px;' ></div>

If you have a countdown, then you must have some sort of end time defined. So instead of having a countdown and just subtracting 1 every second, try something like this:
var endTime = new Date(2011,11,13,0,0,0); // Midnight of December 13th 2011
var timer = setInterval(function() {
var now = new Date();
var timeleft = Math.max(0,Math.floor((endTime.getTime()-now.getTime())/1000));
var d, h, m, s;
s = timeleft % 60;
timeleft = Math.floor(timeleft/60);
m = timeleft % 60;
timeleft = Math.floor(timeleft/60);
h = timeleft % 24;
timeleft = Math.floor(timeleft/24);
d = timeleft;
document.getElementById('counter').innerHTML = "Time left: "+d+" days, "+h+" hours, "+m+" minutes, "+s+" seconds.";
if( timeleft == 0) clearInterval(timer);
},1000);

var interval = 90000; //90 secounds
function reset() {
localStorage.endTime = +new Date() + interval;
}
if (!localStorage.endTime) {
reset();
}
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}
setInterval(function () {
var remaining = localStorage.endTime - new Date();
if (remaining >= 0) {
document.getElementById("tooltip").innerText =
millisToMinutesAndSeconds(remaining);
} else {
reset();
}
}, 100);

Related

Updating the button element as a countdown timer through javascript

I want to create a countdown timer which looks like an fps counter for webpage...
after hours of time spent i m not able to find out what is wrong.....help
<script>
var myvar = setInterval(function () { startTimer() }, 1000);
function startTimer() {
var presentTime = 17 + ":" + 00;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if (s == 59) {
m = m - 1
}
//if(m<0){alert('timer completed')}
var button2 = document.createElement("Button2");
var interval = m + s;
button2.innerHTML = Math.round(interval);
button2.style = "top:0; left:0rem; height:10% ;color: black; background-color: #ffffff;position:fixed;padding:20px;font-size:large;font-weight: bold;";
setTimeout(startTimer, 1000);
document.body.appendChild(button2);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec
}; // add zero in front of numbers < 10
if (sec < 0) {
sec = "59"
};
return sec;
}
</script>
I can find three errors that hinder your code from performing correctly.
Multiple timers
First off since you invoke both a setInterval in outer scope, and then a setTimeout after each performed iteration, you will end up getting many unwanted timer instances that will do some crazy counting for you.
I recommend you to scrap either one of these and stick with just one of them.
For my example i happend to stick with the setInterval since you're executing the very same method over and over any way.
The initialization
Since the presentTime is declared inside the startTimer-function it will be constantly overwritten with 17 + ":" + 00 (resulting in "17:0" btw).
This is solved by declaring it in the outer scope instead.
Remembering the changes
Finally you need to save the current state of presentTime after modifications. Just adding a presentTime = [m,s].join(":"); at the end of startTimer() solves this.
var presentTime = "17:00";
function startTimer() {
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if (s == 59) {
m = m - 1
}
var button2 = document.createElement("Button2");
var interval = s;
button2.innerHTML = m + ":" + s;
button2.style = "top:0; left:0rem; height:10% ;color: black; background-color: #ffffff;position:fixed;padding:20px;font-size:large;font-weight: bold;";
document.body.appendChild(button2);
presentTime = [m,s].join(":");
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec
}; // add zero in front of numbers < 10
if (sec < 0) {
sec = "59"
};
return sec;
}
var interval = setInterval(startTimer, 1000);

JQuery: I want to refresh when countdown reaches zero

I want to refresh when countdown reaches zero.
window.location.reload();
So I added a refresh to countdown <= 0.
However, the refresh is infinite.
How can I do a single refresh after the countdown reaches zero?
The refresh script is:
$(document).ready(function() {
endTimeCheck();
window.setInterval(function() {
endTimeCheck();
}, 1000);
});
var timestamp = Math.floor(Date.now() / 1000);
function endTimeCheck() {
$("span[name='betStatus']").each(function() {
var $span = $(this);
var play_timestamp = parseInt($(this).attr("timestamp"));
var countdown = play_timestamp - timestamp - 32700;
if (countdown <= 0) {
if (!$span.hasClass('closed')) {
$span.css("color", "#FF5733").css("font-weight", "bold").text("finish");
var tdObj = $span.parents('.event-list-item').addClass("disable");
window.location.reload();
}
}
// 30분
else if (countdown < 1800) {
var minute = Math.floor(countdown / 60);
var second = countdown % 60;
if (second < 10) {
second = "0" + second;
}
$(this).css("color", "DarkOrange").css("font-weight", "bold").text(minute + ":" + second);
}
// 1시간
else if (countdown <= 3600) {
var minute = Math.floor(countdown / 60);
var second = countdown % 60;
if (second < 10) {
second = "0" + second;
}
$(this).css("font-weight", "bold").text(minute + ":" + second);
}
});
timestamp++;
}
I think the best way to achieve this is using cookies.
When your countdown reach 0, you set a cookie (ie: refreshed, true).
Don't forget to check if the cookie doesn't exists before your countdown function.
document.cookie = 'refreshed=true';
You can also set an expiration time if you want your function to be re-enabled every 2hs.
var now=new Date();
var expireTime=new Date();
expireTime.setHours(now.getHours()+2);
document.cookie = 'refreshed=true; expires='+expireTime.toGMTString();

pause an interval along a chain

I know this isn't going to help you understand so I'll break it down.
I have a webpage that has an interval for the time, this time is translated into an hour and that loads a audio file. The problem being that the interval reloads the audio every second and I only want it to interval based on the hour and the clock to work as intended. I have it set up like this.
The basic of it is that I have a page loading stuff based on the time of day and I need a way to edit the time live with some function and change the elements. If there is a better way to do this, I am open to suggestions.
note: i can not use jquery
//interval//
var myVar = setInterval(function(){ myTimer() }, 1000);
//get the time//
function myTimer() {
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var time = h + ":" + m + ":" + s;
document.getElementById('time').innerHTML = time;
mod_time(h,m,s)
}
// mod the time //
function mod_time(h,m,s) {
var x = 0;
if(x == 1){
var h = h - h + 2
}
if(x == 2){
var h = h - h + 3
}
else{
var h = h;
}
//applying just the hours//
apply_mod_time(h)
//displaying the full modded time for debugging//
var t_str = h + ":" + m + ":" + s;
document.getElementById('time2').innerHTML = t_str;
}
//playing sound based on the hour//
function apply_mod_time(h) {
if (h==1) {
document.getElementById("myAudio").src = "moo.mp3";
}
}
Add another variable that specifies the current hour. When you execute the interval every second, see if h !== hourVariable. If they do not match, load the audio file and update the hourVariable to equal h.

Daily javascript countdown shorten to jquery

Found this daily countdown timer and edited it a little but I find it a little long and learned that Jquery is a shorter notation of javascript but don't know anything about it.
My knowledge is not advanced enough to either shorten this or change it to jquery.
I use the <body onload = "getSeconds()"> to start the daily countdown.
var reloadPage = false;
function getSeconds()
{
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var midnight = new Date(now.getFullYear(),now.getMonth(),now.getDate(),21,57,0); //midnight 0000 hrs
//midnight - change time hh,mm,ss to whatever time required, e.g. 7,50,0 (0750)
var ft = midnight.getTime() + 86400000; // add one day 86 400 000
var diff = ft - time;
diff = parseInt(diff/1000);
if (diff > 86400) {diff = diff - 86400}
startTimer (diff);
}
var timeInSecs;
var ticker;
function startTimer(secs){
timeInSecs = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); //to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else
{
clearInterval(ticker); //stop counting at zero
if (secs == 0)
{
reloadPage = true;
console.log("reset");
};
getSeconds(); //and start again if required
}
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
if(reloadPage)
{
var result = "Please reload page for daily reset."
}
else
{
var result = ((hours <= 0 ) ? "" : hours + " hours ") + ( (mins <= 0) ? "" : mins + " minutes " ) + ( (mins <= 0) ? " < 1 minute " : "" );
}
document.getElementById("countdown").innerHTML = "Daily reset: " + result;
}
Here's your code "changed to jQuery"
var reloadPage = false;
function getSeconds()
{
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var midnight = new Date(now.getFullYear(),now.getMonth(),now.getDate(),21,57,0); //midnight 0000 hrs
//midnight - change time hh,mm,ss to whatever time required, e.g. 7,50,0 (0750)
var ft = midnight.getTime() + 86400000; // add one day 86 400 000
var diff = ft - time;
diff = parseInt(diff/1000);
if (diff > 86400) {diff = diff - 86400}
startTimer (diff);
}
var timeInSecs;
var ticker;
function startTimer(secs){
timeInSecs = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); //to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else
{
clearInterval(ticker); //stop counting at zero
if (secs == 0)
{
reloadPage = true;
console.log("reset");
};
getSeconds(); //and start again if required
}
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
if(reloadPage)
{
var result = "Please reload page for daily reset."
}
else
{
var result = ((hours <= 0 ) ? "" : hours + " hours ") + ( (mins <= 0) ? "" : mins + " minutes " ) + ( (mins <= 0) ? " < 1 minute " : "" );
}
$("#countdown").html("Daily reset: " + result);
}
saving 27 bytes ... I'm sure loading 86000+ bytes of jQuery library wont negate this saving at all
a shorter implementation, imo. simpler, and no need for jQuery (even if you've already loaded it)
//a few values that come in handy when dealing with timestamps
MILLISECOND = MILLISECONDS = 1;
SECOND = SECONDS = 1000*MILLISECONDS;
MINUTE = MINUTES = 60*SECONDS;
HOUR = HOURS = 60*MINUTES;
DAY = DAYS = 24*HOURS;
TIMEZONE_OFFSET = new Date().getTimezoneOffset() * MINUTES;
var midnight = Date.now() + DAY - (Date.now() - TIMEZONE_OFFSET) % DAY;
function updateCountdown(){
//an utility to fetch the parts (hours, mins, ...) of the time
//and return a formated output
function fetch(factor, postfix){
var value = Math.floor(t/factor);
t %= factor; //beware: side-effect
//format the value
return value > 0?
value + (postfix == null? "": postfix):
"";
}
var t = midnight - Date.now(); //time till midnight
var countdown = document.querySelector("#countdown");
if(t <= 0){
countdown.innerHTML = "Please reload page for daily reset.";
location.reload();
}else{
countdown.innerHTML = [
"Daily reset:",
fetch(HOURS, " hours"),
fetch(MINUTES, " minutes"),
fetch(SECONDS, " seconds")
].join(" ");
setTimeout(updateCountdown, 200);
}
}
updateCountdown();
Edit:
how would I change the time to be resetted at
the variable midnight holds the target-timestamp I am counting to: t = midnight-Date.now()
change the target timestamp.
//a utility that gives you the timestamp for today `00:00 AM` (in your local timezone)
function today(){
var now = Date.now();
return now - (now - TIMEZONE_OFFSET) % DAY;
}
console.log( new Date( today() ) ); //today 00:00:00 GMT+yourTimeZoneOffset
define a target timezone:
var midnight = today() + 1*DAY;
var target = today() + 20*HOURS + 45*MINUTES + 59*SECONDS;
//you see how these constants get handy ;)
and compute the time to that target:
var t = target - Date.now();
the rest is the same

Running a Javascript Clock at 4x Speed [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript to run the Clock (date and time) 4 times speeder
I'm trying to make a clock that starts at a time value (hh:mm:ss) that I've supplied, and runs at 4x speed (for the server time of an online game that runs 4x actual time). I've modified a free clock that I found online to do this, but it only works for every other minute (try the code below to see exactly what I mean if that doesn't make sense).
var customClock = (function () {
var timeDiff;
var timeout;
function addZ(n) {
return (n < 10 ? '0' : '') + n;
}
function formatTime(d) {
t1 = d.getHours();
t2 = d.getMinutes();
t3 = d.getSeconds() * 4;
if (t3 > 59) {
t3 = t3 - 60;
t2 = t2 + 1;
}
if (t2 > 59) {
t2 = t2 - 60;
t1 = t1 + 1;
}
if (t1 > 23) {
t1 = 0;
}
return addZ(t1) + ':' + addZ(t2) + ':' + addZ(t3);
}
return function (s) {
var now = new Date();
var then;
var lag = 1015 - now.getMilliseconds();
if (s) {
s = s.split(':');
then = new Date(now);
then.setHours(+s[0], +s[1], +s[2], 0);
timeDiff = now - then;
}
now = new Date(now - timeDiff);
document.getElementById('clock').innerHTML = formatTime(now);
timeout = setTimeout(customClock, lag);
}
}());
window.onload = function () {
customClock('00:00:00');
};
Any idea why this is happening? I'm pretty new to Javascript and this is definitely a little hack-ey. Thanks
i take the orginal time and substract it from the current then multiply it by 4 and add it to the orginal time. I think that should take care or the sync problem.
(function(){
var startTime = new Date(1987,08,13).valueOf() //save the date 13. august 1987
, interval = setInterval(function() {
var diff = Date.now() - startTime
//multiply the diff by 4 and add to original time
var time = new Date(startTime + (diff*4))
console.log(time.toLocaleTimeString())
}, 1000)
}())
How to use with a custom date (use the Date object)
Date(year, month, day, hours, minutes, seconds, milliseconds)
var lag = 1015 - now.getMilliseconds(); is attempting to "run this again a smidge (15 ms) after the next clock tick". Make this value smaller (divide by 4?), and this code will run more frequently.
Next up, get it to show 4x the current clock duration. Similar problem: multiply now's details by 4 either inside or outside formatTime()
I would first create a Clock constructor as follows:
function Clock(id) {
var clock = this;
var timeout;
var time;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.stop = stop;
this.start = start;
var element = document.getElementById(id);
function stop() {
clearTimeout(timeout);
}
function start() {
timeout = setTimeout(tick, 0);
time = Date.now();
}
function tick() {
time += 1000;
timeout = setTimeout(tick, time - Date.now());
display();
update();
}
function display() {
var hours = clock.hours;
var minutes = clock.minutes;
var seconds = clock.seconds;
hours = hours < 10 ? "0" + hours : "" + hours;
minutes = minutes < 10 ? "0" + minutes : "" + minutes;
seconds = seconds < 10 ? "0" + seconds : "" + seconds;
element.innerHTML = hours + ":" + minutes + ":" + seconds;
}
function update() {
var seconds = clock.seconds += 4;
if (seconds === 60) {
clock.seconds = 0;
var minutes = ++clock.minutes;
if (minutes === 60) {
clock.minutes = 0;
var hours = ++clock.hours;
if (hours === 24) clock.hours = 0;
}
}
}
}
Then you can create a clock and start it like this:
var clock = new Clock("clock");
clock.start();
Here's a demo: http://jsfiddle.net/Nt5XN/

Categories