how to make count timer increase in hour, minute, seconds in javascript? - javascript

i want to make count timer from 00:00:00, the count start if "div id = data" is filled with "const date" and the time increase until the code receive stop trigger. how i can achieve that?
here is my current code :
<div id="data"></div>
<p id="demo"></p>
<script>
const api_url = 'json.php'
async function okejson() {
const resp = await fetch(api_url);
const dat = await resp.json();
const awal = (dat[0])
const date = awal.tanggal
document.getElementById("data").innerHtml = date
var distance = 0;
var x = setInterval(function() {
distance +=1;
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 ";
}, 1000); }
</script>

Using setInterval will not yeild accurate results. It is acceptable for short periods and non critical applications. If it may take hours you should consider using system clock. However here is a constructor which you can use to generate an object which has a start (and also stop and reset) method on it. The start method accepts a callback function which it will call each second and passes an object with days, hours, minutes, and seconds properties. You can use it to do whatever you want.
function Timer() {
this.value = 0
this.updateCb = null
this.interval = null
function getTime() {
console.log(this.value)
var seconds = this.value % 60
var minutes = Math.floor(this.value / 60)
var hours = Math.floor(this.value / 3600)
var days = Math.floor(this.value / (3600 * 24))
return { days: days, hours: hours % 24, minutes: minutes % 60, seconds }
}
this.start = function (cb) {
if (cb) this.updateCb = cb
clearInterval(this.interval)
var self = this
interval = setInterval(function () {
self.value += 1
if (self.updateCb) self.updateCb(getTime.bind(self)())
}, 1000)
}
this.stop = function () {
this.clearInterval(interval)
}
this.reset = function () {
this.value = 0
clearInterval(interval)
}
}
var timer = new Timer()
timer.start(function (time) {
console.log(time)
})
You can start the timer on click of a button or whatever other event.

Related

Javascript/jQuery stop the countup timer

I have function countup.
Below is my code and demo.
Now I need to stop the countup but I don't have any idea how to put and do that on function.
So the idea, I just call this: $("#a").countRunTime().stop() then it will stop the countup.
Any idea?
$.fn.countRunTime = function(fromDate){
var $el = this;
tick();
var options = $.extend({
callback: function() {}
}, arguments[0] || {});
options.callback.call(this);
function formatTime(distance) {
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);
var value = (hours > 9 ? hours : '0' + hours) + ":" + (minutes > 9 ? minutes : '0' + minutes) + ":" + (seconds > 9 ? seconds : '0' + seconds);
return value;
}
function tick() {
var now = new Date().getTime();
if(fromDate > now) {
$el.html("Invalid");
}
else {
var remaining = now-fromDate;
$el.html(formatTime(remaining));
setTimeout(tick, 1000);
}
};
};
$("#a").countRunTime(new Date("20 Jul 2022 11:21:33").getTime());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="a"></div>
There is a way to stop the timer by writing $(“#a).countRunTime().stop(). But I don’t necessarily recommend it for the sake of code clarity. The code would look some like this:
$.fn.countRunTime = function(fromDate) {
var $el = this;
if (!fromDate) { // If fromDate is undefined
return {
stop: () => clearInterval($el.data(“tickInt”))
};
}
var tick = function() {
var now = new Date().getTime();
var remaining = now-fromDate;
$el.html(formatTime(remaining));
}
// Code to start timer
if(fromDate > now) {
$el.html("Invalid");
return;
}
$el.data(“tickInt”, setInterval(tick, 1000));
tick();
}
This works by attaching the tickInt to the element do it doesn’t get lost, by using the $.data function. This function, unlike the dataset attribute, allows you to attach objects of elements. When you run countRunTime without a value for fromDate, it returns an obj with the stop function, allowing $(“a”).countRunTime().stop() to work!
I only don’t recommend this because attaching for functionality to this function will become very challenging and convoluted. Instead, I recommend countRunTime to be assigned to a JSON obj with keys “start” and “stop”. It should look something like this:
$.fn.countRunTime = function () {
var $el = this;
return {
start: function(fromDate) {
function formatTime(distance) {
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);
var value = (hours > 9 ? hours : '0' + hours) + ":" + (minutes > 9 ? minutes : '0' + minutes) + ":" + (seconds > 9 ? seconds : '0' + seconds);
return value;
}
var tick = function() {
var now = new Date().getTime();
var remaining = now-fromDate;
$el.html(formatTime(remaining));
}
// Code to start timer
var now = new Date().getTime();
if(fromDate > now) {
$el.html("Invalid");
return;
}
$el.data("tickInt", setInterval(tick, 1000));
tick();
},
stop: function() {
clearInterval($el.data("tickInt"))
}
}
}
With this code, you can easily expand upon the functionality if needed. It also looks clearer. You can start the timer by typing $("#a").countRunTime().start(new Date("20 Jul 2022 11:21:33").getTime()); and stop it by typing $("#a").countRunTime().stop()
FYI: I nested the JSON obj in a function because I was unsure how else to reference the element by using 'this' without it referencing the JSON obj itself.
NOTE: I left out the $.expand function because I honestly have no clue how it works.

Why does this code do not work? (countdown)

I would like to write a code and a function that takes the name of the event and the date/time of the event and returns the time till the event. I would like to know what is wrong with the code.
<p style="color:red;font-size:20px;" id="C1_Counter"></p>
<script>
CD1(New_Year, "January 1, 2022 00:00:00")
function CD1(event_name, event_date) {
var C1 = "event_name = ";
var C1_Date = new Date(event_date).getTime();
var C1_Counter = document.getElementById("C1_Counter");
setInterval(() => countDown(C1, C1_Date, C1_Counter), 1000);
}
function countDown(x,time, elm) {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the time parameter
var distance = time - 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 we got from the parameter elm
elm.innerHTML = x + days + " days " + hours + " hours "
+ minutes + " minutes " + seconds + " seconds ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
console.log(elm);
elm.innerHTML = "EXPIRED";
}
}
</script>
Currently, your code throws the error ReferenceError: New_Year is not defined (you can see it in the browser console). If I understand correctly, you just forgot the quotes around the string. So try to replace:
CD1(New_Year, "January 1, 2022 00:00:00")
with:
CD1("New_Year", "January 1, 2022 00:00:00")
Also, you need to interpolate an argument into a string. So try to replace:
var C1 = "event_name = ";
with:
var C1 = event_name + " = ";
or with:
var C1 = `${event_name} = `;

How to set a timer that keeps extending itself

I have build a popup with a timer. When the timer ends I want it to extend itself with another day. I have gone so far that it extends itself with 1 day for 1 time but then it quits.
Maybe you have any idea on how to proceed?
Thanks!
//Make countdown
var setInfiniteTime = '{{ $actiepopup->infiniteTime }}';
// Update the count down every 1 second
var x = setInterval(function() {
// Set the date we're counting down to
// Get todays date and time
var currentDate = new Date().getTime();
// get countdown time
var countDownDate = new Date(countDownTimeUntil).getTime();
// console.log('countdowndateBefore' + countDownDate);
// check in infinite time is set
if (setInfiniteTime == 'Yes') {
if (currentDate >= countDownDate) {
// var i;
// for (var i = 0; i < 999999; i++) {
var countDownDate = new Date(countDownTimeUntil).getTime() + 86400000;
// console.log(i);
// }
}
}
// console.log('currentdate' + currentDate);
// console.log('countdowndate' + countDownDate);
// Find the distance between now and the count down date
var distance = countDownDate - currentDate;
// 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="countdown"
$("#countdown").text(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
$("#countdown").text("Actie beeïndigd");
}
}, delayInMilliseconds);
Hope you have enough information!
SetInterval()
Also, just an advice, if you use boolean statements, just use true or false since it's way easier to work with
if (setInfiniteTime) {
setInterval(() => {
var countDownDate = new Date(countDownTimeUntil).getTime() + 86400000
}, 86400000)
}

Countdown Timer in Vanilla Javascript without using a function

I have a project where I need to do a countdown timer, However no function can be used. I know that this can be done with a setInterval, however, most of the documentation I have found shows a function being used in conjunction. W3schools has a great example, however, it used a function. I know how I would do it with
I have already written some code, and was able to display the minutes and seconds, however, cannot get it to actually count down. is there a way to do this without a function?
const timeSpan = document.getElementById('timer');
// Get Time Now
var timeMinutes = 10;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeMinutes * 60 * 1000);
var distance = deadline - currentTime;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
timeSpan.innerHTML = minutes + 's' + seconds;
This shows the minutes and seconds, but without the setInterval or setTimeOut it wont count down like a normal countdown timer. For the project it needs to count down from ten minutes and at the end alert the user that is is expired and that they will need to refresh the page.
You need to move some things out of the function as you are resetting the timer on every interval. You should avoid storing your times as Date objects as well since you only need the timestamps.
const timeSpan = document.getElementById('timer');
const mins = 10;
const now = new Date().getTime();
const deadline = mins * 60 * 1000 + now;
setInterval(() => {
var currentTime = new Date().getTime();
var distance = deadline - currentTime;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
timeSpan.innerHTML = minutes + 's' + seconds;
}, 500)
<span id=timer></span>
<script>
var timer = (mins) => {
const timeSpan = document.getElementById('timer');
const now = new Date().getTime();
const deadline = mins * 60 * 1000 + now;
setInterval(() => {
var currentTime = new Date().getTime();
var distance = deadline - currentTime;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
timeSpan.innerHTML = minutes + ' min. ' + seconds + ' s.';
if (minutes <=0 && seconds <=0) {
alert('Time is over');
return false;
}
}, 1000);
}
timer(10);
</script>
<span id="timer"></span>

NaN on Javascript countdown timer in Internet Explorer

I'm using the following JavaScript for a countdown timer and it has been working great in most browsers, I've just double checked Internet Explorer however and I am getting 'NaN' displayed in place of each number.
Can anyone help to explain where this goes wrong in IE not seeing the individual variables as a number?
// Set the date we're counting down to
var countDownDate = new Date("2018-05-25 12:00: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);
if (days.toString().length < 2) {
days = "0" + days;
}
if (hours.toString().length < 2) {
hours = "0" + hours;
}
if (minutes.toString().length < 2) {
minutes = "0" + minutes;
}
if (seconds.toString().length < 2) {
seconds = "0" + seconds;
}
// Display the result in the element with id="countdown"
document.getElementById("countdown").innerHTML = days + " : " + hours + " : " +
minutes + " : " + seconds;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "<a href='/register'>Countdown Expired</a>";
}
}, 1000);
<span id="countdown"></span>
MDN discourages the use of a string in the date constructor because not all browsers implement this the same way.
If you do want to use date strings, I would recommend using a third party library like momentjs to parse these strings to make sure this works in every browser.
Just normalise the date and time
function getNormalisedDatetime(dString) { // yyyy-mm-dd hh:mm:ss
var parts = dString.split(" ");
var dParts = parts[0].split("-");
var tParts = parts[1].split(":");
return new Date(dParts[0],dParts[1]-1,dParts[2],tParts[0],tParts[1],tParts[2]);
}
function pad(num) {
return ("0"+num).slice(-2);
}
// Set the date we're counting down to
var countDownDate = getNormalisedDatetime("2018-05-25 12:00: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="countdown"
document.getElementById("countdown").innerHTML = "" + pad(days) + " : " + pad(hours) + " : " +
pad(minutes) + " : " + pad(seconds);
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "<a href='/register'>Countdown Expired</a>";
}
}, 1000);
<span id="countdown"></span>

Categories