JS coutdown times not show - javascript

In my site page I have a simple countdown timer:
{{ $tournaments->end }} is parsed information from MySQL, like this: 2020-07-27 03:17:36 and in MySQL field with time has timestamp format.
At my view blade i use:
function create_target_date() {
var target_date = new Date(`2020-07-27 03:17:36`) // {{$tournaments -> end}}
//target_date.setDate(target_date.getDate()+1);
target_date.setHours(23, 59, 59);
return target_date;
}
function calculation_timer() {
var target_date = create_target_date();
var current_date = new Date();
val_timer = target_date.getTime() - current_date.getTime();
var hours = Math.floor(val_timer / 1000 / 60 / 60);
var minutes = Math.floor((val_timer - hours * 60 * 60 * 1000) / 1000 / 60);
var seconds = Math.floor(((val_timer - hours * 60 * 60 * 1000) - minutes * 60 * 1000) / 1000);
document.getElementById('hours').innerHTML = hours;
document.getElementById('minutes').innerHTML = minutes;
document.getElementById('seconds').innerHTML = seconds;
}
function start_timer() {
calculation_timer();
id_timer = setInterval(calculation_timer, 1000);
}
<body onload='start_timer();'>
(<span id='hours'></span><span id='hours_legend'></span>:<span id='minutes'></span><span id='minutes_legend'>:</span><span id='seconds'></span><span id='seconds_legend'></span>)
</span>
</span>
</body>
But nothing don't show, at my page timer doesn't want to show.
If see the source code, it says Uncaught SyntaxError: missing ) after argument list at line var target_date = new Date({{ $tournaments->end }}); and another error start_timer is not defined but i have start_timer() function.
And if see the page source code, it show:
function create_target_date()
{
var target_date = new Date(2020-07-27 03:17:36);
//target_date.setDate(target_date.getDate()+1);
target_date.setHours(23,59,59);
return target_date;
}
I mean date parse sucessful. How i can make the timer show, where is my mistake?

You needed quotes. Here is a slicker version
const pad = num => ("0" + num).slice(-2);
window.addEventListener("load", function() {
const target_date = new Date(`2020-07-27 03:17:36`) // `{{$tournaments -> end}}`
target_date.setHours(23, 59, 59);
const output = document.getElementById("time");
const id_timer = setInterval(function() {
const current_date = new Date();
const diff = target_date.getTime() - current_date.getTime();
const hours = Math.floor(diff / 1000 / 60 / 60);
const minutes = Math.floor((diff - hours * 60 * 60 * 1000) / 1000 / 60);
const seconds = Math.floor(((diff - hours * 60 * 60 * 1000) - minutes * 60 * 1000) / 1000);
time.innerHTML = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`
}, 1000);
})
<span id="time"></span>

Related

how to make count timer increase in hour, minute, seconds in 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.

Count up Timer changes for text output

I'm a real JS novice. I finally found a simple webpage-only script that gives a count up time from a fixed date, and with beginner's luck I tweaked it to give text output in minutes and hours from the supplied span html.
However it shows "Updated 0 hours 9 min ago".
I want to remove the unnecessary '0 hours' until 60 minutes have passed to show: "Updated 9 min ago".
Then show hours again: "Updated 1 hours 1 min ago".
Appreciate any help on this, many thanks.
window.onload = function() {
// Month Day, Year Hour:Minute:Second, id-of-element-container
countUpFromTime("Jan 22, 2020 08:45:30", 'countup1'); // ****** Change this line!
};
function countUpFromTime(countFrom, id) {
countFrom = new Date(countFrom).getTime();
var now = new Date(),
countFrom = new Date(countFrom),
timeDifference = (now - countFrom);
var secondsInADay = 60 * 60 * 1000 * 24,
secondsInAHour = 60 * 60 * 1000;
days = Math.floor(timeDifference / (secondsInADay) * 1);
hours = Math.floor((timeDifference % (secondsInADay)) / (secondsInAHour) * 1);
mins = Math.floor(((timeDifference % (secondsInADay)) % (secondsInAHour)) / (60 * 1000) * 1);
secs = Math.floor((((timeDifference % (secondsInADay)) % (secondsInAHour)) % (60 * 1000)) / 1000 * 1);
var idEl = document.getElementById(id);
idEl.getElementsByClassName('hours')[0].innerHTML = hours;
idEl.getElementsByClassName('minutes')[0].innerHTML = mins;
clearTimeout(countUpFromTime.interval);
countUpFromTime.interval = setTimeout(function(){ countUpFromTime(countFrom, id); }, 1000);
}

Countdown Values keep coming out as undefined in JavaScript

I know there are easier ways to make a countdown Timer, but I need to do it with these three functions.
I tried returning the values of the getRemainingTime function as an Array, but got the same result.
The timer says undefined Tage undefined:undefined:undefined
const ReleaseDate = new Date("April 01, 2020 12:00:00").getTime();
//Calculate Days,Hours,Minutes,Seconds left
function getRemainingTime(CurrentDate, ReleaseDate){
const Differenz = ReleaseDate - CurrentDate;
const d= Math.floor(Differenz / (1000*60*60*24));
const h= Math.floor((Differenz / (1000*60*60*24)) / (1000*60*60));
const m= Math.floor((Differenz / (1000*60*60)) / (1000*60));
const s= Math.floor((Differenz / (1000*60)) / 1000);
//return multiple values as objects
return {d:d, h:h, m:m, s:s};
}
//produce and return strings
function formatDays(days){
return (days + " Tage ");
}
function formatTime(hours, minutes, seconds){
return (hours + ":" + minutes + ":" + seconds);
}
function updateCountdown(){
//repeat every second
const TimerFunction = setInterval(function(){
//calculate time now
const CurrentDate = new Date().getTime();
//call function to calculate days,hours,minutes,seconds
getRemainingTime();
//access Objects
const values = getRemainingTime();
const days = values.d;
const hours = values.h;
const minutes = values.m;
const seconds = values.s;
//call functions to produce strings
formatDays();
formatTime();
document.getElementById("Countdown-Timer").innerText = formatDays() + formatTime();
},1000)
}
//start updateCountdown function
updateCountdown();
const ReleaseDate = new Date("April 01, 2020 12:00:00").getTime();
function getRemainingTime(CurrentDate, ReleaseDate) {
const Differenz = ReleaseDate - CurrentDate;
const d = Math.floor(Differenz / (1000 * 60 * 60 * 24));
const h = Math.floor((Differenz / (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const m = Math.floor((Differenz / (1000 * 60 * 60)) / (1000 * 60));
const s = Math.floor((Differenz / (1000 * 60)) / 1000);
return {
d: d,
h: h,
m: m,
s: s
};
}
function formatDays(days) {
return (days + " Tage ");
}
function formatTime(hours, minutes, seconds) {
return (hours + ":" + minutes + ":" + seconds);
}
function updateCountdown() {
const TimerFunction = setInterval(function () {
const CurrentDate = new Date().getTime();
getRemainingTime(CurrentDate, ReleaseDate);
const values = getRemainingTime(CurrentDate, ReleaseDate);
const days = values.d;
const hours = values.h;
const minutes = values.m;
const seconds = values.s;
formatDays(days);
formatTime(hours, minutes, seconds);
document.getElementById("Countdown-Timer").innerText = (formatDays(days) + formatTime(hours, minutes, seconds));
}, 1000)
}
updateCountdown();

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>

Passing Razor Variable into JavaScript Function

I am working on an Auction site in Asp.net MVC and I am trying to be able to display how a timer of how much time is left on each item's auction. I pass a list of items to my cshtml page with my Model and then iterate through them like so:
My javascript function to start timer:
function countdown(time) {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
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 with id="timeLeft"
document.getElementById("timeLeft").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
}, 1000);
Then my iterator of my Model, calling js function with the item's end date
#foreach (var item in Model)
{
//code here
countdown(#item.EndDate)
<text id="timeLeft"></text>
}
I have my script referenced by <script src="~/Scripts/countdown.js" />
The problem I am having is how to call this js function with a c# razor variable. Doing something basic for one item like:
<body onload= "countdown('#item.EndDate')">
When I put my razor variable it greys out my function.
How do I need to go about passing my variable into my js function?
EX: (with singular Model item)
Try with this syntax:
#foreach (var item in Model)
{
//code here
countdown(`${#item.EndDate}`)
}
If you want to make a timer in javascript, I would use window.setInterval function, then set the second parameter to be time interval.
This function countdown need to pass three parameter
End Year
End Month
End Day
function countdown(endYear,endMonth,endDay) {
window.setInterval(function () { StartCount(endYear, endMonth, endDay, 'andy timer'); }, 1000);
}
function StartCount(endYear,endMonth,endDay){
var now=new Date();
var endDate=new Date(endYear,endMonth-1,endDay);
var leftTime=endDate.getTime() - now.getTime();
var leftSecond=parseInt(leftTime/1000);
var day=Math.floor(leftSecond/(60*60*24));
var hour=Math.floor((leftSecond-day*24*60*60)/3600);
var minute=Math.floor((leftSecond - day * 24 * 60 * 60 - hour * 3600) / 60);
var second = Math.floor(leftSecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60);
document.getElementById("timeLeft").innerHTML = day + "d " + hour + "h "
+ minute + "m " + second + "s ";
}
countdown(2018,10,5)
<div id='timeLeft'></div>
You can use this on the body tag
<body onload= "countdown(#Model.EndDate.Year,#Model.EndDate.Month,#Model.EndDate.Day)">
EDIT
It worked on c# MVC online: https://dotnetfiddle.net/ERcwAb
I figured out a crazy way to do what I was trying to do, might not be efficient, might be a sin to the entire coding community, but here it is:
#foreach (var item in Model)
{
<script>
function countdown(endYear, endMonth, endDay, endHours, endMin, num) {
window.setInterval(function () { StartCount(endYear, endMonth, endDay, endHours, endMin, num); }, 1000);
}
function StartCount(endYear, endMonth, endDay, endHours, endMin, num) {
var now = new Date();
var endDate = new Date(endYear, endMonth - 1, endDay, endHours, endMin);
var leftTime = endDate.getTime() - now.getTime();
var leftSecond = parseInt(leftTime / 1000);
var day = Math.floor(leftSecond / (60 * 60 * 24));
var hour = Math.floor((leftSecond - day * 24 * 60 * 60) / 3600);
var minute = Math.floor((leftSecond - day * 24 * 60 * 60 - hour * 3600) / 60);
var second = Math.floor(leftSecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60);
var id = "timeLeft" + num;
document.getElementById(id).innerHTML = day + "d " + hour + "h "
+ minute + "m " + second + "s ";
}
countdown(#item.EndDate.Year, #item.EndDate.Month, #item.EndDate.Day,#item.EndDate.Hour, #item.EndDate.Minute, #num)
</script>
#{string countNum = "timeLeft" + num;}
<text id= #countNum></text>
#{num++;}
//code
}
But it still loads asynchronously where the items will all load, then the clocks all appear a second later and all content is moved accordingly. May be due to my initial issue of not doing able to call body onload.

Categories