Pure JS countdown timer - javascript

I am trying to create a countdown timer, when i click on a button the timer will run according to the value 5, 15, 30 .
I could create a timer but my problem when using the set interval is i can't pass argument to the callback function, when i run the callback function with a preset value it runs fine, but when i am passing an argument it crashes,
var currentTime = new Date();
function displayCurrentTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var display = document.getElementById('now');
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
return(new Date().getTime());
}
setInterval(displayCurrentTime, 1000);
function endTime(m) {
var display = document.getElementById('endTime');
var endingTime = new Date(currentTime.getTime() + (m * 60 * 1000));
var hours = endingTime.getHours();
var minutes = endingTime.getMinutes();
var seconds = endingTime.getSeconds();
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
return endingTime.getTime();
}
function counter() {
var display = document.getElementById('counter');
var countingTime = endTime(1) - displayCurrentTime();
var days = Math.floor(countingTime / (1000 * 60 * 60 * 24));
var hours = Math.floor((countingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((countingTime % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((countingTime % (1000 * 60)) / 1000);
return (display.innerHTML = (hours + '.' + minutes + '.' + seconds));
}
<button id="5" onclick="setInterval(counter, 1000)">5</button>
<button id="15" onclick="setInterval(counter, 1000)">15</button>
<button id="30" onclick="setInterval(counter, 1000)">30</button>
<h3>Current Time</h3>
<p id="now"></p>
<h3>Your time will end at</h3>
<p id="endTime"></p>
<h3>You still have</h3>
<p id="counter"></p>

You can pass any arguments that you want after the delay param in the setInterval. Eg. setInterval(foo, 1000, bar). bar will be passed as a argument to foo every second.

I would simply set the end-time on click and start the counter. So your counter
var endTime = null;
function displayCurrentTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var display = document.getElementById('now');
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
//just call counter here if endTime is set. in this case you only need to call updateEndTime on click
//if(endTime != null) {
// counter();
//}
}
//to avoid 1 second delay on start up
displayCurrentTime()
setInterval(displayCurrentTime, 1000);
function updateEndTime(m) {
var display = document.getElementById('endTime');
var currentTime = new Date();
endTime = new Date(currentTime.getTime() + (m * 60 * 1000));
var hours = endTime.getHours();
var minutes = endTime.getMinutes();
var seconds = endTime.getSeconds();
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
}
function counter() {
var display = document.getElementById('counter');
var currentTime = new Date();
var countingTime = endTime - currentTime;
var days = Math.floor(countingTime / (1000 * 60 * 60 * 24));
var hours = Math.floor((countingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((countingTime % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((countingTime % (1000 * 60)) / 1000);
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
}
<button id="5" onclick="updateEndTime(5);counter();setInterval(counter, 1000)">5</button>
<button id="15" onclick="updateEndTime(15);counter();setInterval(counter, 1000)">15</button>
<button id="30" onclick="updateEndTime(30);counter();setInterval(counter, 1000)">30</button>
<h3>Current Time</h3>
<p id="now"></p>
<h3>Your time will end at</h3>
<p id="endTime"></p>
<h3>You still have</h3>
<p id="counter"></p>
Btw. you probably should only use 1 setInterval and update both counters in 1 call checking if endTime is set or not

Related

jQuery/Javascript make callback for countdown

I have jquery countdown function with below code:
$.fn.countdown = function(toTime, callback){
let $el = $(this);
var intervalId;
let timeUpdate = () => {
var now = new Date().getTime();
var distance = toTime - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
if(distance < 0){
clearInterval(intervalId);
}
else{
var value = days + "<sup>d</sup> " + (hours > 9 ? hours : '0' + hours) + ":" + (minutes > 9 ? minutes : '0' + minutes) + ":" + (seconds > 9 ? seconds : '0' + seconds);
$el.html(value);
}
if(callback) callback();
}
timeUpdate();
intervalId = setInterval(timeUpdate, 1000);
};
$('#my_div').countdown(new Date("Jun 23, 2022 22:37:25").getTime());
$('#my_div2').countdown(new Date("Jun 23, 2022 22:20:25").getTime());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div"></div>
<div id="my_div2"></div>
Now I need to add callback function if the time has finished.
My idea is like this:
$('#my_div').countdown(new Date("Jun 23, 2022 22:37:25").getTime(), function(){
callback: function() {
alert("Counting Finish");
}
});
Is there any way to implement that callback?
Your code is almost there, there's just two issues. Firstly you need to invoke the callback argument from within the distance < 0 block, as that's what determines when the countdown has ended. Secondly you need to provide an actual callback argument to the countdown() call.
Note in the following example I made the countdowns only a few seconds from the current date to make the demo clearer.
$.fn.countdown = function(toTime, callback) {
let $el = $(this);
var intervalId;
let timeUpdate = () => {
var now = new Date().getTime();
var distance = toTime - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
if (distance < 0) {
clearInterval(intervalId);
callback && callback();
} else {
var value = days + "<sup>d</sup> " + (hours > 9 ? hours : '0' + hours) + ":" + (minutes > 9 ? minutes : '0' + minutes) + ":" + (seconds > 9 ? seconds : '0' + seconds);
$el.html(value);
}
}
timeUpdate();
intervalId = setInterval(timeUpdate, 1000);
};
var date1 = new Date();
date1.setSeconds(date1.getSeconds() + 5);
$('#my_div').countdown(date1.getTime(), () => console.log('first countdown elapsed!'));
var date2 = new Date();
date2.setSeconds(date2.getSeconds() + 10);
$('#my_div2').countdown(date2.getTime(), () => console.log('second countdown elapsed!'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div"></div>
<div id="my_div2"></div>

I want make a local timer

i want make a local countdown for 1H & i want code to pause the timer & resume it of course! & i searched on web but i found codes that work to count incoming days
PS: code is demo from w3schools (but it's still counting incoming days so yeah)
var countDownDate = new Date("Jan 5, 2019 15:37:25").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
expected results: code counting 1h
actual results: code counting incoming days
Starting from your code, you can get what you want with just a few changes:
const ONE_HOUR_ON_MILLIS = 1000 * 60 * 60;
var countDownDate;
var running;
var remainingMillis;
var update;
initCountdown();
function startInterval() {
return setInterval(function () {
var now = new Date().getTime();
remainingMillis = countDownDate - now;
var hours = Math.floor((remainingMillis % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((remainingMillis % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((remainingMillis % (1000 * 60)) / 1000);
var millis = Math.floor((remainingMillis % 1000));
document.getElementById("demo").innerHTML = hours + ":" + minutes + ":" + seconds + "." + millis;
if (remainingMillis < 0) {
clearInterval(update);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 10);
}
function stop() {
if (running) {
var now = new Date().getTime();
remainingMillis = countDownDate - now;
running = false;
clearInterval(update);
} else {
alert('cant stop');
}
}
function start() {
if (!running) {
countDownDate = new Date().getTime() + remainingMillis;
update = startInterval();
running = true;
}
}
function initCountdown() {
countDownDate = new Date().getTime() + ONE_HOUR_ON_MILLIS;
update = startInterval();
running = true;
}
function restart() {
initCountdown();
debugger;
}
<span id="demo">COUNTDOWN</span>
<div class="controls">
<button id="start" onclick="start()">Start</button>
<button id="stop" onclick="stop()">Stop</button>
<button id="restart" onclick="restart()">Restart</button>
</div>
This should do what you want.

Countdown timer expires start a different countdown

I have the following code. I want when this timer expires, another timer should start instead of expired text.
var countDownDate = new Date("Oct 25, 2017 15:37:25").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
document.getElementById("demo").innerHTML = days + " Days " + hours + " Hrs "
+ minutes + " Min " + seconds + " Sec ";
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "T**imer Expired - instead of this another timer**";
}
}, 1000);
Create a function, and call it every time the timer is finished.
$(document).ready(function() {
var i = 1 ;
setTimer(i) ;
}) ;
function setTimer(i) {
var countDownDate = new Date().getTime() + 3000 ;
var x = setInterval(function() {
var now = new Date().getTime() ;
var distance = countDownDate - now ;
if (distance < 0) {
clearInterval(x);
console.log("Timer " + i + " Finished. New Timer Stated!") ;
setTimer(i+1) ;
}
else {
console.log("Timer " + i + " Running") ;
}
}, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This code should do the trick. Each time the counter get to 0, you redefined your count down to the same amount of time there was initially between countDownDate and Now. If this amount is variable, you might modify the assignment of distanceToAdd
// Changed the value to reach for the demo
var countDownDate = new Date().getTime() + 20000;
// Fixed Value to add each time the counter get to 0
var distanceToAdd = countDownDate - new Date().getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
if (distance < 0) {
//Add Time to your timer goal instead of canceling interval
countDownDate += distanceToAdd;
}
else {
document.getElementById("demo").innerHTML = days + " Days " + hours + " Hrs "
+ minutes + " Min " + seconds + " Sec ";
}
}, 1000);
<html>
<head>
</head>
<body>
<div id="demo"></div>
</body>
</html>

JavaScript count-up timer

I want to add the count-up timer which will count from specified time.
I want to do this as follows:
I would add the button "reset" and after it's clicked the timer starts and counts forever from that specified time, but if I press it again in the future it counts time from that specified time in the future.
var countDownDate = new Date();
// 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 an the count down date
var distance = countDownDate.getTime() + now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}, 1000);
I have code like this but the output is very wrong.
Here is the link: JSFiddle
Use localStorage to save the date
var countDownDate = localStorage.getItem('startDate');
if (countDownDate) {
countDownDate = new Date(countDownDate);
} else {
countDownDate = new Date();
localStorage.setItem('startDate', countDownDate);
}
// 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 an the count down date
var distance = now - countDownDate.getTime();
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}, 1000);
https://jsfiddle.net/5a6ranep/1/
<!doctype html>
<html>
<body>
<button onclick="console.log(getTimeElapsed());">Log Time Elapsed</button>
<script type="application/javascript">
var startTime = Date.now(); // Get Starting time in MS
var endTime = 0;
var timeElapsed = 0;
function getTimeElapsed() {
endTime = Date.now(); // Get current Time
timeElapsed = endTime - startTime; // current time - startTime = Time Elapsed
startTime = Date.now();
return timeElapsed * 0.001; // Convert MS to S
}
</script>
</body>
</html>

Execute code from text input in countdown function

In the following code I want to make a text input field (for a date) which gets executed so that the countdown timer is set to that value and starts counting - for example after clicking "OK" button. I don't really know how to modify the first variable in order to do that.
<script>
// Set the date we're counting down to
var countDownDate = new Date("May 25, 2018 11:30:00").getTime();
// 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 an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = "Pozostało: </br>" + days + " Dni, </br>" + hours + "g : " + minutes + "m : " + seconds + "s";
document.getElementById("demo").style.fontSize = "45px";
document.getElementById("demo").style.fontWeight = "bold";
document.getElementById("demo").style.color = "white";
document.getElementById("demo").style.backgroundColor = "#4783bf";
document.getElementById("demo").style.textAlign ="center";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
Thank you for all the advice!
Have a look at this fiddle start timer on click of button
I have entered this date in textbox :- May 26, 2017 01:30:00
function startTimer(){
var dateEntered = document.getElementById("txtDate").value;
// Set the date we're counting down to
//May 26, 2017 01:30:00
var countDownDate = new Date(dateEntered).getTime();
// 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 an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = "Pozostało: </br>" + days + " Dni, </br>" + hours + "g : " + minutes + "m : " + seconds + "s";
document.getElementById("demo").style.fontSize = "45px";
document.getElementById("demo").style.fontWeight = "bold";
document.getElementById("demo").style.color = "white";
document.getElementById("demo").style.backgroundColor = "#4783bf";
document.getElementById("demo").style.textAlign ="center";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
<input type="text" id="txtDate"/>
<br>
<input type="button" value="Calculate" onclick="startTimer();">
<div id="demo">
</div>
The first, you need to download datetimepicker library.
https://plugins.jquery.com/datetimepicker/
And then, following this. Remember to change the path of css and jquery files.
<link href="~/css/jquery.datetimepicker.css" rel="stylesheet" />
<body>
<input type="text" id="datetimepicker" />
<input type="button" value="Ok" id="btOk" />
<p id="demo" />
</body>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/jquery.datetimepicker.min.js"></script>
<script type="text/javascript">
$('#datetimepicker').datetimepicker();
$(document).ready(function () {
$('#btOk').click(function () {
var currentDate = $('#datetimepicker').val();
var countDownDate = new Date(currentDate).getTime();
// 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 an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = "Pozostało: </br>" + days + " Dni, </br>" + hours + "g : " + minutes + "m : " + seconds + "s";
document.getElementById("demo").style.fontSize = "45px";
document.getElementById("demo").style.fontWeight = "bold";
document.getElementById("demo").style.color = "white";
document.getElementById("demo").style.backgroundColor = "#4783bf";
document.getElementById("demo").style.textAlign = "center";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
});
});
</script>

Categories

Resources