admin管理员组文章数量:1430693
How to set cookie for this count down timer? The cookie should prevent resetting timer while I am refreshing the page.
<div id="hms">02:00:00</div>
<script type="text/javascript">
function count() {
var startTime = document.getElementById('hms').innerHTML;
var pieces = startTime.split(':');
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(' ')[0];
document.getElementById('hms').innerHTML = newtime;
setTimeout(count,1000);
}
count();
</script>
How to set cookie for this count down timer? The cookie should prevent resetting timer while I am refreshing the page.
<div id="hms">02:00:00</div>
<script type="text/javascript">
function count() {
var startTime = document.getElementById('hms').innerHTML;
var pieces = startTime.split(':');
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(' ')[0];
document.getElementById('hms').innerHTML = newtime;
setTimeout(count,1000);
}
count();
</script>
Share
Improve this question
edited Jun 7, 2016 at 9:51
user6413892
asked Jun 3, 2016 at 4:52
Namatullah ShahbaziNamatullah Shahbazi
2381 gold badge9 silver badges22 bronze badges
1
- 2 How about code instead of image ? – Rayon Commented Jun 3, 2016 at 4:54
3 Answers
Reset to default 6The problem is if you save the time in cookie just before refresh and retrieve it after page loads it may not match the real current time because page may take arbitrary amount of time to refresh, 1st time it may be 1 sec 2nd time may be faster and take 0.5 sec due to factors like caching etc. for users on slower network it may be always more than 1-2 seconds. So the time on the page will always lag and won't match the real current time after a few refreshes.
Looks like i was wrong browser don't refresh the content already on the page until all required resources are downloaded so your counter keeps going as well as setting cookies until its all ready
Here is what i got to work
<html>
<body>
<div id="hms">02:00:00</div>
</body>
<script>
var startTime;
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
} // credits kirlich @http://stackoverflow./questions/10730362/get-cookie-by-name
function count() {
if(typeof getCookie('remaining')!= 'undefined')
{
startTime = getCookie('remaining');
}
else if(document.getElementById('hms').innerHTML.trim()!='')
{
startTime = document.getElementById('hms').innerHTML;
}
else
{
var d = new Date();
var h=d.getHours();
var m=d.getMinutes();
var s=d.getSeconds();
startTime = h+':'+m+':'+s;
//OR
startTime = d.toTimeString().split(" ")[0]
}
var pieces = startTime.split(":");
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timediff = new Date(time.valueOf()-1000)
var newtime = timediff.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML=newtime ;
document.cookie = "remaining="+newtime;
setTimeout(count,1000);
}
count();
</script>
</html>
PS: Tried and tested the countdown survives page refresh and accurate even in heavy page throttling >10 seconds!
If you don't want current time but any manual time entered you can always adjust the values to get the desired effect.
I think you need to use document.cookie = newtime
. So every time when you assign newtime to element on the same time newtime should also be assigned to cookie so it may not be lost.
Simple:
Let's assume you need 2 clocks, each with different duration time (if you need more than 2 clocks, or only one, just extrapolate the explanation).
- Set running and stopped clock styles:
.runningClock, stoppedClock
{width:75px;
color:white;
font-weight:bold;
border:3px double white
}
.runningClock { background:#1ABB9C; /* use your favorite green/turquoise */ }
.stoppedClock { background:red; }
- Create each clock in HTML with an ID (I'm using DIV, but it can be a TD, a SPAN or other block object) [ignore extra spaces below, typed here to make code visible]:
- < div id=clock1>< /div>
- < div id=clock2>< /div>
- within your JS block, build these 2 functions:
function Secs2Clock( numSecs ) { // converts # of seconds to a digital clock format )
return ( parseInt( numSecs /3600 ).toString().padStart(2,"0") + ':' +
(parseInt( (numSecs /60) )%60).toString().padStart(2,"0") + ':' +
parseInt( numSecs %60 ).toString().padStart(2,"0") );
}
function runClock( oneClock, hours, minutes ) {
var secs=hours*minutes*60;
oneClock.className="runningClock"; // sets it to paint green, running
var runningClock=setInterval( function() { //starts clock refreshing by second
oneClock.innerHTML = Secs2Clock( secs );
if ( secs>0 ) secs-- // single instruction if true, feel free to add curled brackets for readability
else {
oneClock.innerHTML="00:00:00";
oneClock.className="stoppedClock";
clearInterval( runningClock );
}
}, 1000
);
}
- Within your main JS block (or your "BODY onLoad" function or wherever you want the clock[s] to launch), add this line for each clock (in this example, 2 different ones); or else within the onClick action or whatever action (A HREF click, etc) where you want the specific clock(s) to start (in this example, this is part of the main JS code, to launch both clocks with different remaining times)
runClock( clock1, 1, 0 ); // will start as "01:00:00"
runClock( clock2, 6, 30 ); // will start as "06:30:00"
本文标签: javascriptCountdown timer for hoursminutesand secondsStack Overflow
版权声明:本文标题:javascript - Countdown timer for hours, minutes, and seconds - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745424966a2658067.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论