How to get the timer start counting down using javascript? - javascript

I am trying to make a timer start counting down. I think my next step is to make the countdown function to actually work. What would be the best approach for this?
JavaScript and HTML codes below:
// Set the default timer as 25:00
var timer = document.getElementById("mytime");
var counter = setInterval(function(){
countdown()}, 1000);
//user clicks the 'start' button and timer starts counting down
function countdown(minutes, seconds){
timer.value = "17:30:00"; //default value
document.getElementById("btn").innterHTML = counter;
counter--;
};
var click = document.getElementById("btn");
btn.addEventListener("click", countdown); //"click" as DOM Object?
btn.addEventListener("click", stopcounting);
<head>
<title>Pomodoro Timer</title>
</head>
<body>
<h1>POMODORO TIMER</h1>
<div id="main">
<input type="time" id="mytime">
<button id="btn"> start </button>
</div>
</body>

This is my own version of the clock where you can start the timer by adding the specific time when the event happened. Please see the below code.
// Set the date we're counting down to
var start_at = new Date('2020-06-29 12:00:00');
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date();
// Find the distance between now an the count down date
var distance = now - start_at;
// 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").value = hours + "h "
+ minutes + "m " + seconds + "s ";
}, 1000);

This may be what you want, I haven't done it in the date time format but you can pretty much convert that by yourself.
<head>
<title>Pomodoro Timer</title>
</head>
<body>
<h1>POMODORO TIMER</h1>
<div id="main">
<input id="mytime" value=1000>
<button id="btn"> start </button>
</div>
</body>
<script>
var input = document.getElementById("mytime");
var button = document.getElementById("btn");
var started = false;
var timer;
var startTimer = function (count) {
return setInterval(function () {
input.setAttribute("value", --count);
}, 1000);
}
button.addEventListener("click", function () {
if (!started) {
var count = parseInt(input.getAttribute("value"));
timer = startTimer(count);
started = true;
button.innerHTML = "stop";
} else {
clearInterval(timer);
started = false;
button.innerHTML = "start";
}
});
</script>
JSFiddler: https://jsfiddle.net/m7pev0vm/

Your code is a bit jumbled. So let me help you sort it out.
First off, the click function needs to trigger a the start of countdown.
The counter in the timer function would need to be something in seconds. So that you can keep decrementing the value while on the face of it, it would be in hours, minutes & seconds.
Also, You need to have a target time. So if I say counter until 00:00:00 then the following could work, as an example :
// Set the default timer as 5:30 PM
var timer = document.getElementById("mytime");
var counter = (17*60*60) + (30*60);
timer.value = "17:30:00"; //default value
function countdown(minutes, seconds){
--counter;
var hrs = Math.floor(counter / 3600),
min = Math.floor((counter % 3600) / 60),
sec = Math.floor((counter % 3600) % 60);
timer.value = hrs + ":" + min + ":" + sec;
};
function onClick() {
var counter = setInterval(function(){
countdown();
}, 1000);
//user clicks the 'start' button and timer starts counting down
}
var click = document.getElementById("btn");
btn.addEventListener("click", onClick); //"click" as DOM Object?
btn.addEventListener("click", stopcounting);
<head>
<title>Pomodoro Timer</title>
</head>
<body>
<h1>POMODORO TIMER</h1>
<div id="main">
<input type="time" id="mytime">
<button id="btn"> start </button>
</div>
</body>

I know this is coming very late but I know it will help someone someday.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
<input type="text" name="demo" id="demo" size="20" readonly="true" style="text-align:center;"/>
<br>
</form>
<script>
// Set the date we're counting down to
var countDownDate = new Date().getTime() + ((1)*60*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 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);
// Output the result in an element with id="demo"
document.getElementById("demo").value = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down remains 15 minutes, write some text
if (minutes == 59 && seconds == 1) {
alert("Hello! 1 minute gone");
}
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo");
demo.value= "EXPIRED";
}
}, 1000);
</script>
</body>
</html>

Related

Update date object assigned variable

This is a count up timer, counting up in time from when the page is loaded, I was to make a function called resetcountupDate() which sets it back to zero by making the variable countupDate equal to the current date (using date() or something), and I want the button on the 4th to last line to do the function, my code below doesn't work in terms of resetting the timer.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" , charset="UTF-8">
<style>
#import url('https://fonts.googleapis.com/css2?family=Roboto+Slab:wght#100&display=swap');
p {
font-family: 'Roboto Slab', serif;
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
<p></p>
<p></p>
<p></p>
<p></p>
<script>
// Set the date we're counting up from
var countupDate = new Date();
function resetcountupDate() {
var countupDate;
countupDate = Date();
}
// Update the count up 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 up date
var distance = now - countupDate;
// 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);
</script>
<input type=button value="Show Time" onclick="resetcountupDate();">
</body>
</html>
The main problem is your countupDate used in interval has global scope, so redefine it in reset... won't affect your expected variables
function resetcountupDate() {
countupDate = new Date() // just this only
}
Furthermore, I suggest some additional changes to make it feel more like reseting. First, I made a function that return an interval, so when reset, it first stop the interval. Second, I also made display a separated function, along with making days, hours, minutes, seconds global scope, so when reset, I also set all of these variables to 0, display the initial, and start the interval again
function resetcountupDate() {
clearInterval(x)
days = hours = minutes = seconds = 0
display()
countupDate = new Date()
x = startInterval()
}
// Set the date we're counting up from
var countupDate = new Date()
var days, hours, minutes, seconds
function display() {
document.getElementById("demo").innerHTML =
days + "d " + hours + "h " + minutes + "m " + seconds + "s "
}
function startInterval() {
return setInterval(function () {
// Get today's date and time
var now = new Date().getTime()
// Find the distance between now and the count up date
var distance = now - countupDate
// Time calculations for days, hours, minutes and seconds
days = Math.floor(distance / (1000 * 60 * 60 * 24))
hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
seconds = Math.floor((distance % (1000 * 60)) / 1000)
// Output the result in an element with id="demo"
display()
}, 1000)
}
function resetcountupDate() {
clearInterval(x)
days = hours = minutes = seconds = 0
display()
countupDate = new Date()
x = startInterval()
}
// Update the count up every 1 second
var x = startInterval()
#import url('https://fonts.googleapis.com/css2?family=Roboto+Slab:wght#100&display=swap');
p {
font-family: 'Roboto Slab', serif;
text-align: center;
font-size: 60px;
margin-top: 0px;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" , charset="UTF-8">
</head>
<body>
<p id="demo"></p>
<p></p>
<p></p>
<p></p>
<p></p>
<input type=button value="Show Time" onclick="resetcountupDate();">
</body>
</html>

Count Down Timer With User Input To Modify End Date

Is there a way to take this pre-existing code and make it so that instead of having the end date as a preset value. have it so that the user can select an end date using date inputs and time inputs. I there a way to do this by only Using HTML and Javascript with an onClick() function to avoid using PHP. Any help that I can get would be extremely helpful.
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
// 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 = 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);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</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>
End Date <input type="datetime-local" id="endDate">
<button onclick="countdownTimeStart()">Start Timer</button>
<script>
// Set the date we're counting down to
function countdownTimeStart(){
var endDate = document.getElementById('endDate').value;
var dateObject = new Date(endDate);
var countDownDate = new Date(dateObject).getTime();
// 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 = 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);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
</script>
</body>
</html>

Calculating countdown by hours \ minutes instead of seconds

I"m trying to use this countdown but it calculates the time every second.
I want to counter to count the time by minutes or even hours, not every second because i only display days and hours.
I've tryied to remove the var seconds or minutes but the inspect elemnts showing me a purplr blink on the timer every 1 second meaning it's still calculating the time by seconds.
<!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("April 24, 2018 15:37:25").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);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
</body>
</html>
Change
// Update the count down every 1 second
var x = setInterval(function() {
...
}, 1000);
to
// Update the count down every 1 minute
var x = setInterval(function() {
...
}, 1000*60);
or
// Update the count down every 1 hour
var x = setInterval(function() {
...
}, 1000*60*60);
Edit
That will update your timer every minute/hour. Now, to start countdown and update every minute/hour:
calculateCountdown();
// Update the count down every 1 minute
var x = setInterval(function() {
calculateDountdown();
}, 1000*60);
or just
calculateCountdown();
setInterval(calculateCountdown, 1000*60);
where
function calculateCountdown() {
// 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);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}
Check this answer to see how to refactor setInterval based solution to setTimeout based.

How to display an image after countdown timer finishes?

I am trying to display a full screen image after a jQuery countdown timer has finished but I am confused how to do this within my jQuery/css/html scripts
My jQuery code is as follows:
//Sets the date and time the clock is counting down to
var countDownDate = new Date("August 23, 2017 17:43:00").getTime();
//Updates the counter every second
var x = setInterval(function() {
//Get today's date and time
var now = new Date().getTime();
// Finding the length of time between now and 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);
//Output the result in an element with an id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// if the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = " you've been screwed over by Theresa May";
function myFunction() {
var m = document.getElementsByClassName("image");
m[0].innerHTML = "image";
}
}
}, 1000);
My HTML is as follows:
<!DOCTYPE HTML>
<html>
<head>
<title>Brexit Countdown 2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href ="Brexit2.css" rel="stylesheet" type="text/css"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script>
<script src="Brexit2.js"></script>
</head>
<body>
<h1>Brexit Countdown</h1>
<p id="demo"></p>
</body>
</html>
My CSS is as follows-
p {
text-align: center;
font-size: 80px;
}
h1 {
text-align: center;
font-size: 200px;
}
As mentioned at the beginning I simply want to display an image along with a statement after the countdown finally finishes. I really would appreciate some help here. Many thanks.
//Consider this function to display the image and the <p>
function myFunction() {
document.getElementById("displayImage").style="display:block";
}
//This calls the myFunction() in the set time.
setInterval(myFunction, 5000);
//5000 is in milliseconds, which is 5 seconds.
<div id="displayImage" style="display:none">
<img src="https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png">
<p>Assume that this is the image you wanna display...</p>
</div>
Please use this JSFiddle as reference. Please set the countDownDate to a future time, else it wont work.
Demo: here
Code:
//Sets the date and time the clock is counting down to
var countDownDate = new Date("August 23, 2017 23:29:00").getTime();
//Updates the counter every second
var x = setInterval(function() {
//Get today's date and time
var now = new Date().getTime();
// Finding the length of time between now and 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);
//Output the result in an element with an id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// if the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = " you've been screwed over <br> by Theresa May";
var m = document.getElementsByClassName("image");
m[0].src = "https://upload.wikimedia.org/wikipedia/commons/7/79/Operation_Upshot-Knothole_-_Badger_001.jpg";
}
}, 1000);
A common way is to add the image to the html, but to hide it using a css class.
HTML:
<img id="hiddenImage" class="hiddenClass" src="someSource.jpg">
CSS:
.hiddenClass {
display: none;
}
Then, using jQuery or vanilla JS, you either change the CSS class to something else, or to remove the class.
jQuery:
// find by id, the jQuery way
var image = $('#hiddenImage');
// remove the class that was hiding the image before
// this will make it visible by default
image.removeClass('hiddenClass');
JsFiddle Demo: https://jsfiddle.net/jonahe/rxprv1c0/

JavaScript timer not working on multiple instance

Below is a result of a loop and I want to run timer to count up to the set time for each of the loop result.
<span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>
<span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>
<span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>
The timer script:
$(document).ready(function(){
$('[data-time]').each(function() {
console.log($(this))
var $this = $(this),
finalTime = $(this).data('time'),
url = $(this).data('url')
// Set the date we're counting down to
var countDownDate = new Date(finalTime).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 an element with id="demo"
document.getElementById("time").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("time").innerHTML = "EXPIRED";
}
}, 1000);
})
})
So am using Laravel and jQuery to run the timer.
I want assistance with the code because it is not working.
The trick is to "save" you intervals in an array.
If you do not do it, it gets overwritten on each loop iteration.
Then, to refer to the right span element, you have to get the iteration index for later use in an .eq() method.
You can't use an id in a loop, since it has to be unique.
Have a look at comments within the code.
$(document).ready(function(){
// an arrary to store the intervals created.
var timerArray = [];
$('[data-time]').each(function(index) {
console.log($(this).data("time"));
var finalTime = $(this).data('time');
// Set the date we're counting down to
var countDownDate = new Date(finalTime).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// this Index will be used to refer to the right span.
var thisIndex = index;
console.log("interval "+thisIndex);
// 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);
// Leading zeros...
if(hours<10){hours="0"+hours}
if(minutes<10){minutes="0"+minutes}
if(seconds<10){seconds="0"+seconds}
// Display the result in an element with id="demo"
$('[data-time]').eq(thisIndex).html( days + "d " + hours + "h " + minutes + "m " + seconds + "s " );
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(timerArray[thisIndex]);
$('[data-time]').eq(thisIndex).html("EXPIRED");
}
}, 1000);
// Place this timer in an array... So it won't be overwritten.
timerArray.push(x);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span data-time="07/08/2017 12:30:00"></span><br>
<br>
<span data-time="07/10/2017 19:50:30"></span><br>
<br>
<span data-time="07/12/2017 5:24:24"></span><br>
<br>
Run the snippet in "full page" or look at this CodePen.

Categories