I can't seem to figure out why my countdownclock function keeps restarting after reaching 00:00. It gets to 00:00 but then restarts from whatever I put in the prompt. I believe I need to add a condition such as a while #time != "00:00" but I'm not entirely sure how.
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
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) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function() {
var choice = prompt("Minutes to launch")
var setTheClock = 60 * choice,
display = document.querySelector('#time');
startTimer(setTheClock, display);
};
<body style="width: 100vw; padding: 0; border: 0; margin: 0;">
<div style="width: 60vh; padding: 0; border: 0; margin: 0 auto;">
<p id="time" style="font-family:futura; font-size: 20vh; text-align: center; padding: 0; border: 0; margin-top: 40vh"></p>
</div>
</body>
You need to clear the interval. Set the interval to a variable and clear it when it's finished otherwise, it will keep on going.
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
var interval;
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
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) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
clearInterval(interval);
}
};
// we don't want to wait a full second before the timer starts
timer();
interval = setInterval(timer, 1000);
}
window.onload = function() {
var choice = prompt("Minutes to launch")
var setTheClock = 60 * choice,
display = document.querySelector('#time');
startTimer(setTheClock, display);
};
<body style="width: 100vw; padding: 0; border: 0; margin: 0;">
<div style="width: 60vh; padding: 0; border: 0; margin: 0 auto;">
<p id="time" style="font-family:futura; font-size: 20vh; text-align: center; padding: 0; border: 0; margin-top: 40vh"></p>
</div>
</body>
You need to store the interval in a variable and clear it when total time gets to 0.
Working solution.
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds,
countDownTimer;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
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) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
clearInterval(countDownTimer);
}
}
// we don't want to wait a full second before the timer starts
timer();
countDownTimer = setInterval(timer, 1000);
}
window.onload = function() {
var choice = prompt("Minutes to launch")
var setTheClock = 60 * choice,
display = document.querySelector('#time');
startTimer(setTheClock, display);
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body style="width: 100vw; padding: 0; border: 0; margin: 0;">
<div style="width: 60vh; padding: 0; border: 0; margin: 0 auto;">
<p id="time" style="font-family:futura; font-size: 20vh; text-align: center; padding: 0; border: 0; margin-top: 40vh"></p>
</div>
</body>
</html>
Related
var date = new Date;
var s = date.getSeconds();
var m = date.getMinutes();
var h = date.getHours();
setTimeout(function () {
$('#offer1').fadeOut('fast');
$('#remainingTime').fadeOut('fast');
}, 8640000);
function Timer(duration, display) {
var timer = duration, hours, minutes, seconds;
setInterval(function () {
hours = parseInt((timer / 3600) % 24, 10)
minutes = parseInt((timer / 60) % 60, 10)
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(parseInt(hours-h) + ":" + parseInt(minutes-m) + ":" + parseInt(seconds-s));
--timer;
}, 1000);
}
jQuery(function ($) {
var twentyFourHours = 24 * 60 * 60;
var display = $('#remainingTime');
Timer(twentyFourHours, display);
});
var i =$("remainingTime").textContent;
console.log(i);
<div class="ml-2">Time Remaining <span id="remainingTime">24:00:00</span></div>
<div id="offer1">asdf</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
Here, I've made a timer which says how much time is left for 24 Hours.
But it's showing Hours, Minutes and seconds in negative value for seconds after a minute and negative value for minutes after an Hour.
I need the both div elements ("offer1" and "remainingTime") should fade out after 24 hours timer.
By using the current Date and getTime() I should show the time remaining
Here is the JSFiddle Link https://jsfiddle.net/Manoj07/d28khLmf/2/...
Thanks for everyone who tried to help me. And here is the answer
https://jsfiddle.net/Manoj07/1fyb4xv9/1/
Hello this code works for me
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<div class="ml-2">Time Remaining <span id="remainingTime"></span></div>
<div id="offer1">asdf</div>
<script>
// this code set time to 24 hrs
var timer2 = "24:00:00";
/*
if you want to get timer from localstorage
var session_timer = localStorage.getItem('timer');
if(session_timer){
console.log('timer',session_timer);
timer2 = session_timer;
}
*/
var interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var hours = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
hours = (minutes < 0) ? --hours : hours;
if (hours < 0) clearInterval(interval);
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hours = (hours < 10) ? '0' + hours : hours;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 10) ? minutes : minutes;
timer2 = hours+ ':' +minutes + ':' + seconds;
if(hours <= 0 && minutes == 0 && seconds == 0){
// if you want to delete it on local storage
// localStorage.removeItem('timer');
console.log('finish')
// fade out div element
$( "#offer1" ).fadeOut( "slow", function() {
// Animation complete.
});
}
else{
$('#remainingTime').html(timer2);
// if you want to save it on local storage
// localStorage.setItem('timer', timer2);
}
}, 1000);
</script>
createCountdown returns a countdown object with two methods: start and stop.
A countdown has a to date, an onTick callback, and a granularity.
The granularity is the frequency at which the onTick callback is invoked. So if you set a granularity of 1000ms, then the countdown will only tick once a second.
Once the difference between now and to is zero, the onComplete callback is called, and this hides the DOM node.
This solution uses requestAnimationFrame which will have a maximum resolution of about 16 milliseconds. Given that this is the maximum speed that the screen is updated, this is fine for our purposes.
const $ = document.querySelector.bind(document)
const now = Date.now
const raf = requestAnimationFrame
const caf = cancelAnimationFrame
const defaultText = '--:--:--:--'
const createCountdown = ({ to, onTick, onComplete = () => {}, granularityMs = 1, rafId = null }) => {
const start = (value = to - now(), grain = null, latestGrain = null) => {
const tick = () => {
value = to - now()
if(value <= 0) return onTick(0) && onComplete()
latestGrain = Math.trunc(value / granularityMs)
if (grain !== latestGrain) onTick(value)
grain = latestGrain
rafId = raf(tick)
}
rafId = raf(tick)
}
const stop = () => caf(rafId)
return { start, stop }
}
const ho = (ms) => String(Math.trunc((ms/1000/60/60))).padStart(2, '0')
const mi = (ms) => String(Math.trunc((ms%(1000*60*60))/60000)).padStart(2, '0')
const se = (ms) => String(Math.trunc((ms%(1000*60))/1000)).padStart(2, '0')
const ms = (ms) => String(Math.trunc((ms%(1000)))).padStart(3, '0')
const onTick = (value) => $('#output').innerText = `${ho(value)}:${mi(value)}:${se(value)}:${ms(value)}`
const onComplete = () => $('#toFade').classList.add('hidden')
const to = Date.now() + (2 * 60 * 1000)
const { start, stop } = createCountdown({ to, onTick, onComplete })
$('button#start').addEventListener('click', start)
$('button#stop').addEventListener('click', () => (stop(), $('#output').innerText = defaultText))
div#toFade {
opacity: 1;
transition: opacity 5s linear 0s;
}
div#toFade.hidden {
opacity: 0;
}
div {
padding: 20px;
}
<button id="start">Start</button>
<button id="stop">Stop</button>
<div id="output">--:--:--:--</div>
<div id="toFade">This is the element to fade out.</div>
See https://www.w3schools.com/howto/howto_js_countdown.asp for the code used to create a countdown timer
See how to get tomorrow's date: JavaScript, get date of the next day
// Set the date we're counting down to
const today = new Date()
const tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = tomorrow - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
hours = ("00" + hours).slice(-2);
minutes = ("00" + minutes).slice(-2);
seconds = ("00" + seconds).slice(-2);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = 'Time Remaining: '+hours + ":"
+ minutes + ":" + seconds;
// If the count down is over, hide the countdown
if (distance < 0) {
$("#demo").hide();
}
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
</body>
</html>
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>
// Set the date we're counting down to
var countDownDate = new Date();
countDownDate.setTime(countDownDate.getTime() + (30 * 60 * 1000));
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var minutes = Math.floor((distance/1000/60)%60);
var seconds = Math.floor((distance /1000) % 60);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
</body>
</html>
I want the output with 2 numbers in minute and 2 numbers in seconds like 09:06
I tried with slice(-2) but it didn´t work properly, so i want to know other options to try
Im so newbie with js and this things
Just check if it's under 10 and if so add a leading 0:
var minutes = (Math.floor((distance/1000/60)%60)<10?'0':'') + Math.floor((distance/1000/60)%60);
var seconds = (Math.floor((distance /1000) % 60)<10?'0':'') + Math.floor((distance /1000) % 60);
There are a few ways to do this.
Check if number is less than 10 and prepend 0 if so
function checkTime(num){
if(num<10){
return "0"+num
}
return num
}
<body>
<div>Expires In <span id="time">05:00</span> minutes!</div>
</body>
<script>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
</script>
// Set the date we're counting down to
var countDownDate = new Date();
countDownDate.setTime(countDownDate.getTime() + (30 * 60 * 1000));
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var minutes = Math.floor((distance/1000/60)%60);
var seconds = Math.floor((distance /1000) % 60);
// Output the result in an element with id="demo"\
if (minutes.toString().length == 1)minutes= "0" + minutes;
if (seconds.toString().length == 1)seconds= "0" + seconds;
document.getElementById("demo").innerHTML = minutes+":"+seconds;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date();
countDownDate.setTime(countDownDate.getTime() + (30 * 60 * 1000));
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var minutes = Math.floor((distance / 1000 / 60) % 60);
var seconds = Math.floor((distance / 1000) % 60);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = ("0" + minutes).slice(-2) + "m " + ("0" + seconds).slice(-2) + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1);
</script>
</body>
</html>
Replace the following line in your code
document.getElementById("demo").innerHTML = minutes + "m " + seconds + "s ";
with
document.getElementById("demo").innerHTML = ("0" + minutes).slice(-2) + "m " + ("0" + seconds).slice(-2) + "s ";
Explanation :
In the code, you need to prepend every digit with a “0” and return the last two characters with slice(-2). This way JavaScript will add a leading zero to every one-digit number but leave two-digit numbers intact.
For example:
(“05”).slice(-2) = “05”;
(“018”).slice(-2) = “18”;
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;
}
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
</head>
<body>
<div id="timer">
Time Left: 00:<input id="minutes" type="text" style="width: 20px; border: none; background-color:none; font-size: 16px; font-weight: bold;">:<input id="seconds" type="text" style="width: 26px; border: none; background-color:none; font-size: 16px; font-weight: bold;">
</div>
<script>
countdown();
</script>
In this java script code the timer get executing after the time is over and time goes in minus example (00-1:30).
So I want to stop the timer when it reaches the 00:00. And it should give alert when the time is completed or submit the page.
There are a couple of issues, the biggest being that you are testing the seconds and not seconds.value, so you are always entering the else block. However, you also don't have a condition for when it reaches zero. Here is a jsfiddle that should fix those things, http://jsfiddle.net/psQb5/.
there are two possibilities. One is to use the function setInterval instead of setTimeout. Like this.
<script type="text/javascript">
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
var intervalVar;
function countdown() {
intervalVar = setInterval('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
if (secs == 0) {
window.clearTimeout(intervalVar);
alert('timeout');
}
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
use setInterval() function instead of setTimeout().
when you want to stop timer using clearInterval() function.
for basic understanding of above function click below
w3schools.