I have a countdown until Christmas. But I am not able to make this countdown stops after it reaches the exact date.
function countdown(){
var now = new Date();
var eventDate = new Date(2016, 11, 25);
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
// remaining time in miliseconds
var remTime = eventTime - currentTime;
// converting into seconds, minutes, hours, days
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
var d = Math.floor(h / 24);
// finding exact hours, minutes and seconds
h %= 24;
m %= 60;
s %= 60;
d = (d < 10) ? "0" + d : d;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
document.getElementById("days").innerHTML = d;
document.getElementById("hours").innerHTML = h;
document.getElementById("minutes").innerHTML = m;
document.getElementById("seconds").innerHTML = s;
setInterval(countdown, 1000);
}
countdown();
body {
background: #1f262e;
}
.countdownContainer{
position: absolute;;
top: 50%;
left: 50%;
transform : translateX(-50%) translateY(-50%);
text-align: center;
color: #eff0f2;
padding: 10px;
}
.info {
font-size: 80px;
}
#days, #hours, #minutes, #seconds {
background: #0F1A20;
box-shadow: 0 0 5px 3px #1f262e;
font-size: 120px;
padding: 20px;
}
.title {
font-size: 20px;
}
<table class="countdownContainer" cellspacing="10">
<tr class="title">
<td style="padding-bottom: 20px">DAYS</td>
<td style="padding-bottom: 20px">HOURS</td>
<td style="padding-bottom: 20px">MINUTES</td>
<td style="padding-bottom: 20px">SECONDS</td>
</tr>
<tr class="info" >
<td id="days" border-spacing="10px"></td>
<td id="hours"></td>
<td id="minutes"></td>
<td id="seconds"></td>
</tr>
</table>
I looked at some examples and they are using clearInterval, but i am not sure how am i able to use it here.
Thanks
It's a simple problem , here are some suggestions
Use setTimeout() instead of setInterval() because the former is a one-time event whereas the latter isn't so your set'ed intervals will keep on accumulating over and over , every second one additional is getting added untill browser gets overloaded or crash ? Well idk (browsers are pretty smart these days) but still clearing that enormous mess would require a huge army of clearInterval()s but did you note down the unique identifier for each setInterval() ? Oh no....
At each call eventTime and currentTime are being calculated (they are essentially unix timestamp in millisecs.) so even though former stays the same throughout the run , you would see the latter increase by 1000 upon each call , eventually a time comes when the latter equals/surpasses the former this is where you stop the process.
https://jsfiddle.net/oq2g7h0L/
You can use clearInterval like this
var myVar = setInterval(countdown, 1000);
function myStopFunction() {
clearInterval(myVar);
}
Try using clearTimeout.
var count;
function countdown() {
count = setTimeout('decrement()', 1000);
}
clearTimeout(count);
You don't check if the dates are equal.
If today is the wanted date, then you should stop the interval from running.
interval runs your function every milliseconds you give him as the second argument, so your function will run every second.
var myInterval = setInterval(countdown, 1000);
function countdown(){
var now = new Date();
var eventDate = new Date(2016, 11, 25);
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
// if today is equal Christmas date stop everything
if (currentTime == eventTime) {
return clearInterval(myInterval);
}
// remaining time in miliseconds
var remTime = eventTime - currentTime;
// converting into seconds, minutes, hours, days
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
var d = Math.floor(h / 24);
// finding exact hours, minutes and seconds
h %= 24;
m %= 60;
s %= 60;
d = (d < 10) ? "0" + d : d;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
document.getElementById("days").innerHTML = d;
document.getElementById("hours").innerHTML = h;
document.getElementById("minutes").innerHTML = m;
document.getElementById("seconds").innerHTML = s;
}
Related
I'm trying to add 7 days when the timer reaches 0.
Can you help?
It currently reaches negative values, but I want it to restart every Tuesdays for example.
Also, I found some solutions, but the timer was countdown was reset also on page refresh, and I don't want that.
// Countdown timer
function makeTimer() {
var endTime = new Date("October 18, 2020 08:00:00 EST");
var endTime = (Date.parse(endTime)) / 1000;
var now = new Date();
var now = (Date.parse(now) / 1000);
var timeLeft = endTime - now;
var days = Math.floor(timeLeft / 86400);
var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600 )) / 60);
var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
if (hours < "10") { hours = "0" + hours; }
if (minutes < "10") { minutes = "0" + minutes; }
if (seconds < "10") { seconds = "0" + seconds; }
$("#days").html(days + '<span class="camp">Days</span>');
$("#hours").html(hours + '<span class="camp">Hours</span>');
$("#minutes").html(minutes + '<span class="camp">Minutes</span>');
$("#seconds").html(seconds + '<span class="camp">Seconds</span>');
}
setInterval(function() { makeTimer();
}, 1000);
You have to give the browser a way to know what your end time is or it will go back to the original hardcoded value every time. Either store the data you need to start and end the calculations for a user on the server or use localStorage to do it in the browser only.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
So I've added a function called add7Days and I've got a check to see if the time left is less than 0.
This will add extra days to your variable each time it runs out.
I've also created an object as a global variable because if you are running this presumably for weeks you will start to run into memory leak issue if you are re-declaring the variables every second.
var countDownObject = {
'endDate': new Date('2020-10-19 23:45')
,'now': undefined
,'days': 0
,'hours': 0
,'minutes': 0
,'seconds': 0
,'timeLeft': 0
};
function countDown(){
countDownObject.now = new Date();
countDownObject.timeLeft = countDownObject.endDate - countDownObject.now;
if(timeLeft < 0) add7Days(); /* Function to change time left */
countDownObject.days = Math.floor(timeLeft / 86400);
countDownObject.hours = Math.floor((timeLeft - (days * 86400)) / 3600);
countDownObject.minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600 )) / 60);
countDownObject.seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
if(hours < 10) countDownObject.hours = "0" + hours;
if(minutes < 10) countDownObject.minutes = "0" + minutes;
if(seconds < 10) countDownObject.seconds = "0" + seconds;
$("#days").html(countDownObject.days + '<span class="camp">Days</span>');
$("#hours").html(countDownObject.hours + '<span class="camp">Hours</span>');
$("#minutes").html(countDownObject.minutes + '<span class="camp">Minutes</span>');
$("#seconds").html(countDownObject.seconds + '<span class="camp">Seconds</span>');
};
function add7Days(){
countDownObject.endDate.setDate(countDownObject.endDate.getDate() + 7);
countDownObject.timeLeft = countDownObject.endDate - countDownObject.now;
};
setInterval(function(){makeTimer();}, 1000);
[Edit]
If you are refreshing the browser you may want to store the object countDownObject as either local storage
//Set Object
localStorage.setItem("countDownObject", JSON.stringify(countDownObject));
//Get Object
var countDownObject = JSON.parse(localStorage.getItem("countDownObject"));
or as its own json file on the server.
An alternate approach for counting down to a specific day of the week and time, based on a specific time zone (Tuesday at 8AM, east coast time in your case) would be to use a third-party time API that you could access using an XMLHttpRequest (or fetch if you don’t need to support Internet Explorer).
The third-party time API would give you a JSON object with GMT time with the current offset for eastern time (I used New York for my JSFiddle example) for standard time or daylight savings time, and it would also note if daylight savings was in effect or not. This could be better than depending on the visitor’s computer time, which could be set to a different time zone (e.g. Phoenix, Arizona uses Mountain Standard Time year round).
Having access to a third party time API would let you resync your timer every so often, so the countdown timer wouldn’t drift too far from the actual end time. setInterval can be slow by around 0.3%, which over a 6 day period would be around 30 minutes.
XMLHttpRequest has an onerror event handler that could be used to connect to an alternative time API if the primary one is offline for some reason. IE10 and 11 support the onerror event handler.
// padStart polyfill for IE
if (!String.prototype.padStart) {
String.prototype.padStart = function padStart(targetLength, padString) {
//floor if number or convert non-number to 0;
targetLength = targetLength >> 0;
padString = String(typeof padString !== 'undefined' ? padString : ' ');
if (this.length > targetLength) {
return String(this);
} else {
targetLength = targetLength - this.length;
if (targetLength > padString.length) {
//append to original to ensure we are longer than needed
padString += padString.repeat(targetLength / padString.length);
}
return padString.slice(0, targetLength) + String(this);
}
};
}
function countdownTime (endDay, endTimeStr, reachedZero) {
var oReq;
var endingTimeObj;
var currentDateObj;
var countdownDisplay = document.getElementById("countdown");
var timeDisplay = document.getElementById("time");
var intervalID = null;
var endTime = {};
var numbers = endTimeStr.split(",").map(Number);
var cycleCount = 0;
endTime.hr = numbers[0];
endTime.min = numbers[1];
endTime.sec = numbers[2];
endTime.ms = numbers[3];
function countdown () {
var remainingDays;
var remainingHours;
var remainingMin;
var remainingSec;
var delta = endingTimeObj - currentDateObj;
if (delta <= 0) {
reachedZero(); // call the passed in function
endingTimeObj.setUTCDate(endingTimeObj.getUTCDate() + 7);
delta = endingTimeObj - currentDateObj;
}
remainingDays = Math.floor(delta / 86400000);
delta = delta - remainingDays * 86400000;
remainingHours = Math.floor(delta / 3600000);
delta = delta - remainingHours * 3600000;
remainingMin = Math.floor(delta / 60000);
delta = delta - remainingMin * 60000;
remainingSec = Math.floor(delta / 1000);
timeDisplay.innerHTML = remainingDays + ":" +
remainingHours.toString().padStart(2, "0") + ":" +
remainingMin.toString().padStart(2, "0") + "." +
remainingSec.toString().padStart(2, "0");
currentDateObj.setSeconds(currentDateObj.getSeconds() + 1);
// Sync the countdown after an hour to prevent too much drift
cycleCount += 1;
if (cycleCount >= 3600) {
load();
}
}
function reqListener () {
if(this.readyState === 4 && this.status === 200) {
// Stop the existing timer - will create a new timer in a moment
if (intervalID !== null) {
window.clearInterval(intervalID);
intervalID = null;
}
var obj = JSON.parse(this.responseText);
currentDateObj = new Date(obj.datetime);
endingTimeObj = new Date(obj.datetime);
console.log("GMT: " + currentDateObj.toUTCString());
currentDateObj.setHours(currentDateObj.getHours()
+ parseInt(obj.utc_offset,10));
console.log("ET: " + currentDateObj.toUTCString());
// Time to the next countdown finish
endingTimeObj.setUTCDate(currentDateObj.getUTCDate()
+ (7 + endDay - currentDateObj.getUTCDay()) % 7);
endingTimeObj.setUTCHours(endTime.hr, endTime.min, endTime.sec, endTime.ms);
if (currentDateObj > endingTimeObj) {
endingTimeObj.setUTCDate(endingTimeObj.getUTCDate() + 7);
}
console.log("End: " + endingTimeObj.toUTCString());
// display is initially hidden when first loaded
countdownDisplay.style.display = "block";
countdown();
intervalID = window.setInterval(countdown, 1000);
}
}
function load() {
cycleCount = 0;
oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
if (oReq.onerror !== undefined) {
// A function to connect to a different time API could go
// here (IE9 doesn't support onerror)
}
oReq.open("GET", "https://worldtimeapi.org/api/timezone/America/New_York");
oReq.send();
}
window.onload = load;
if ("visibilityState" in document) {
document.addEventListener("visibilitychange", function() {
if (document.visibilityState === "visible") {
load();
}
});
}
}
function reachedZeroAlert () {
document.body.style.backgroundColor = "red";
alert("Done");
document.body.style.backgroundColor = "white";
}
// Pass in the day (Sunday = 0),
// a string for the time of day the countdown should finish,
// an the function to execute when the countdown reaches zero
countdownTime(2, "08,0,0,0", reachedZeroAlert);
body {
background-color: white;
}
span {
margin: 0;
padding: 0;
}
#countdown {
font-family: monospace;
display: none;
}
.values {
font-size: 2rem;
margin-left: 0.625rem;
}
.labels {
font-size: 0.8rem;
}
.days {
margin-left: 0.1875rem;
}
.hours {
margin-left: 1.0625rem;
}
.minutes {
margin-left: 1.875rem;
}
.seconds {
margin-left: 1.5625rem;
}
<div id="countdown">
<div class="values">
<span id="time">5:22:43.04</span>
</div>
<div class="labels">
<span class="days">Days</span>
<span class="hours">Hr</span>
<span class="minutes">Min</span>
<span class="seconds">Sec</span>
</div>
</div>
Need to create a countdown timer for a online quiz.
Timer should start as soon as user enters web-page.
Tried this piece of code.
<
script >
var fiveMinutes = 3600;
var display = document.getElementById('time');
var myTimer;
function startTime(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
display.textContent = "TIME IS UP!";
clearInterval(myTimer);
}
};
timer();
myTimer = setInterval(timer, 1000);
}
window.onload = function() {
startTime(fiveMinutes, display);
};
Counting is required not from the current moment, but from the date specified in the startTime variable. Let's consider for your convenience that it has exactly the same format as the return value of Date.now ().
i need to get a variable, give it some value (not Date.now ()), and use it as a starting point
thanks beforehand
Not sure if this is what you are looking for, but this is a simple count down timer that displays the time in the window.
const display = document.getElementById('time');
const fiveminutes = 5 * 60 * 1000;
function timer(endTime) {
var myTimer = setInterval(function() {
let now = new Date().getTime();
let diff = endTime - now;
let minutes = Math.floor(diff % (1000 * 60 * 60) / (1000 * 60));
let seconds = Math.floor(diff % (1000 * 60) / 1000);
minutes = minutes < 10 ? `0${minutes}` : minutes;
seconds = seconds < 10 ? `0${seconds}` : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
display.textContent = "TIME IS UP!";
clearInterval(myTimer);
}
}, 100);
}
window.onload = timer(new Date().getTime() + fiveminutes);
span {
font-family: calibri;
font-size: 4em;
}
<body>
<span id="time"></span>
So I'm not sure if this is what you're looking for. This will trigger when the user enters the page. Your comment is confusing though. Do you want this to start when page loads or at a certain time based on a variable?
window.onload(function() {
setTimeout(function() {
// whatever you want to happen after 3600
// i.e. disable input fields for quiz
}, 3600);
}
This is something I'd been working on that I adapted to try to provide a solution for you here. It's still buggy, but maybe it will give you some ideas, and I'll try to edit it when I have some more time. (I expected to have it working by now but need some rest.)
const
timeInput = document.getElementById("timeInput"),
nowBtn = document.getElementById("nowBtn"),
durationInput = document.getElementById("durationInput"),
confirmBtn = document.getElementById("confirmBtn"),
display = document.getElementById("display");
let
startTime,
timeRemaining,
chronos;
document.addEventListener("click", setUpTimer);
timeInput.addEventListener("focus", ()=>{ nowBtn.checked = false; });
function setUpTimer(event){
// Makes sure the button was the target of the click before proceeding
if(event.target == confirmBtn){
if(nowBtn.checked){ // Puts the current time in the time input
const
clickTime = new Date(),
hours = clickTime.getHours();
let minutes = clickTime.getMinutes();
clickTime.setSeconds(clickTime.getSeconds() + 1);
minutes = minutes < 10 ? "0" + minutes : minutes;
timeInput.value = `${hours}:${minutes}`;
}
const
timeInputValue = timeInput.value,
durationInputValue = durationInput.value;
// Validates input (or complains and aborts)
if(!timeInputValue || !durationInputValue){
display.innerHTML = "Please choose a start time and duration"
clearInterval(chronos);
return;
}
const
startArray = timeInputValue.split(":"),
startHours = parseInt(startArray[0]),
startMinutes = parseInt(startArray[1]),
durationInMinutes = parseInt(durationInput.value),
now = new Date();
// Updates global variables that `countdown` function will need
timeRemaining = durationInMinutes * 60;
startTime = new Date();
startTime.setHours(startHours, startMinutes);
// In case startTime is supposed to be tomorrow
const
nowHrs = now.getHours(),
strtHrs = startTime.getHours()
nowMins = now.getMinutes(),
strtMins = startTime.getMinutes();
// If it looks like the hour already passed, it's probably an earlier hour tomorrow
if(strtHrs < nowHrs || (strtHrs == nowHrs && strtMins < nowMins)){
startTime.setDate(startTime.getDate() + 1);
}
// Announces successful timer setup and resets inputs
const
displayedHours = startTime.getHours(),
storedMinutes = startTime.getMinutes(),
displayedMinutes = storedMinutes < 10 ? "0" + storedMinutes : storedMinutes;
display.innerHTML = `A ${durationInMinutes}-minute timer will start ` + `at ${displayedHours}:${displayedMinutes}`;
timeInput.value = "";
nowBtn.checked = false;
durationInput.value = "5";
// `setInterval` calls `countdown` function every second
console.log(startTime.toLocaleString());
clearInterval(chronos);
chronos = setInterval(countdown, 1000);
}
}
function countdown(){
if(timeRemaining <= 0){
display.innerHTML = "TIME IS UP!";
clearInterval(chronos);
}
else{
const now = new Date();
if(now.getTime() >= startTime.getTime()){
updateDisplayedTime(timeRemaining--);
}
}
}
function updateDisplayedTime(totalSeconds){
let
minutes = Math.floor(totalSeconds / 60),
seconds = totalSeconds % 60;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.innerHTML = `${minutes}:${seconds}`;
}
.inputContainer{ margin-bottom: 1em; }
#display{ font-size: 1.7em;}
#nowBtn {margin-left: 1em; }
<div class="inputContainer">
<label>
<div>Start timer at: </div>
<input type="time" id="timeInput" />
</label>
<label>
<input type ="checkbox" id="nowBtn" />
<span>Now</span>
</label>
</div>
<div class="inputContainer">
<label>
<div>Duration (minutes): </div>
<input type="number" value="5" id="durationInput" min="1" max="1440" />
</label>
</div>
<div class="inputContainer">
<button id="confirmBtn">Confirm</button>
</div>
<div id="display"></div>
I have a timer which I am testing, it seems there is a bit of drift between when the minute countdown goes down by 1 and seconds whenever it reaches 59 seconds ()ie every minute:-
How can I alter this so they are both in sync?
my code is the following:-
$(document).ready(function() {
function now() {
return window.performance ? window.performance.now() : Date.now();
}
function tick() {
var timeRemaining = countdown - ((now() - initTick) / 1000);
timeRemaining = timeRemaining >= 0 ? timeRemaining : 0;
var countdownMinutes = Math.floor(timeRemaining / 60);
var countdownSeconds = timeRemaining.toFixed() % 60;
countdownTimer.innerHTML = countdownMinutes + ":" + countdownSeconds;
if (countdownSeconds < 10) {
countdownTimer.innerHTML = countdownMinutes + ":" + 0 + countdownSeconds;
}
if (timeRemaining > 0) {
setTimeout(tick, delay);
}
}
var countdown = 600; // time in seconds until user may login again
var delay = 20; // time (in ms) per tick
var initTick = now(); // timestamp (in ms) when script is initialized
var countdownTimer = document.querySelector(".timer"); // element to have countdown written to
setTimeout(tick, delay);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="timer"></div>
js fiddle: https://jsfiddle.net/robbiemcmullen/cer8qemt/1/
The issue is the precision is not the same for minutes and seconds.
You need to round to the nearest second before /60 / %60.
Consider: exactly 9 mins remaining:
var x = 540;
console.log(x.toFixed() % 60, Math.floor(x / 60));`
Output is: (0,9)
Then consider the call 20 ms later:
var x = 539.980;
console.log(x.toFixed() % 60, Math.floor(x / 60));
the output is now: (0, 8).
So the seconds haven't changed (yet) but the minute does.
Here is a version using setInterval and removing the use of .toFixed ()
Why do you use an interval of 20ms and not 1 second?
//method for countdown timer
$(document).ready(function() {
function now() {
return window.performance ? window.performance.now() : Date.now();
}
function tick() {
var timeRemaining = countdown - elapsedTime;
var countdownMinutes = Math.floor(timeRemaining / 60);
var countdownSeconds = timeRemaining % 60;
countdownTimer.innerHTML = countdownMinutes + ":" + countdownSeconds;
if (countdownSeconds < 10) {
countdownTimer.innerHTML = countdownMinutes + ":" + 0 + countdownSeconds;
}
++elapsedTime;
return timeRemaining;
}
var countdown = 600;
var elapsedTime = 0;
var timeRemaining;
// countdown: time in seconds until user may login again
//var delay = 20;
// delay: time (in ms) per tick
var initTick = now(); // initTick: timestamp (in ms) when script is initialized
var countdownTimer = document.querySelector(".timer");
// countdownTimer: element to have countdown written to
var interval = setInterval(function() {
if(tick() <= 0) {
clearInterval(interval);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timer"></div>
js fiddle https://jsfiddle.net/ud3wm8t1/
i seem to have found a small problem on my scoreboard. If i set it for example, to exactly 1 minute (1:00), it would do 1:0-1 then 0:59. I don't quite understand why it does that, Here's my code:
var minutes = 0;
var c = 0;
var secondes = 0;
var commence = setInterval(commencer, 1000);
clearInterval(commence);
function commencer(){
secondes -= 1;
document.getElementById('temps').innerHTML = minutes + ":" + secondes;
if (secondes < 10) {
document.getElementById('temps').innerHTML = minutes + ":" + c + secondes;
}
if (secondes <= 0) {
secondes = 60;
minutes = minutes - 1;
if (minutes < 0) {
clearInterval(commence);
minutes = 0;
secondes = 0;
clique = 0;
}
}
}
Because that's what you told it to do.
You started with 1 minutes 0 seconds (actually you didn't, but let's assume your code is changed to match your question).
Then you subtracted one second, to get 1 minutes -1 seconds
You wrote this to the HTML
Then you performed arithmetic to handle the underflow, to get 0 minutes 59 seconds
One second later, repeat
Change the order around and it'll work more as you expected:
// Changed minutes from 0 to 1
var minutes = 1;
var c = 0;
var secondes = 0;
var commence = setInterval(commencer, 1000);
// Removed "clearInterval" call that stops the
// whole thing from running
function commencer() {
secondes -= 1;
// This has moved up
if (secondes <= 0) {
secondes = 60;
minutes = minutes - 1;
if (minutes < 0) {
clearInterval(commence);
minutes = 0;
secondes = 0;
clique = 0;
}
}
// This has moved down
document.getElementById('temps').innerHTML = minutes + ":" + secondes;
if (secondes < 10) {
document.getElementById('temps').innerHTML = minutes + ":" + c + secondes;
}
}
<span id="temps"></span>
Your new problem is that the underflow checker sets seconds to 60, so you end up with 0:60. I doubt this is what you intended.
I would now change if (secondes <= 0) to if (secondes < 0) and change secondes = 60 to secondes = 59, though I haven't verified that this is correct; I'll leave that as an exercise for you.
You can add the following code for 1 minute timer, it will also pad 0 while it counts down. just place the div id=clockdiv, add class for seconds and minutes and it should be displayed properly.
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
return {
'total': t,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date(Date.parse(new Date()) + 60 * 1000);
initializeClock('clockdiv', deadline);
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/