I have created a countdown timer which counts down to 5pm every day then resets to 5pm the following day.
The timer works perfectly, but I am getting 2 errors from the code which I am Struggling to solve.
The code is below:
function startTimer(display) {
var date = new Date();
var h17 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 17);
if(date.getHours() >= 17) {
h17.setDate(h17.getDate()+1);
}
h17 = h17.getTime();
var diff,
hours,
minutes,
seconds;
function timer() {
diff = (((h17 - Date.now()) / 1000) | 0);
// Setting and displaying hours, minutes, seconds
hours = (diff / 3600) | 0;
minutes = ((diff % 3600) / 60) | 0;
seconds = (diff % 60) | 0;
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
};
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var display = document.querySelector('#time');
startTimer(display);
};
The errors are looking like line 14: diff = (((h17 - Date.now()) / 1000) | 0);
Returning the message : "Object doesn't support this property or method: line 14"
and line 25: display.textContent = hours + ":" + minutes + ":" + seconds;
Returning the message "Cannot set property 'textContent' of null".
Turns out the issue was coming from binding the output to the #time ID in the html.
Since I had put the script in the and only used this on certain pages, the error was coming from the pages where there was no <div id="time">, so the display was null.
I have fixed this by checking if the element ID exists before running the script.
if(document.getElementById("time")){
var display = document.querySelector('#time');
startTimer(display);
} else {
}
Related
I'm trying to create a counter that shows how much time you've spent on the site and I use sessionStorage to access the Date object from multiple pages.
The problem is that the counter starts at 01:00:00 even though I initialized the Date with 00:00:00.
Here is my code:
function checkTime(){
if(document.getElementById("clock")[13] == ''){
var d = new Date('2010-06-11T00:00:00');
sessionStorage.setItem('time', d);
}
}
function updateTime(){
checkTime();
var nDate = new Date(sessionStorage.getItem('time'));
nDate.setSeconds(nDate.getSeconds() + 1);
sessionStorage.setItem('time', nDate);
var hours = (nDate.getHours()<10 ? "0" : "") + nDate.getHours();
var minutes = (nDate.getMinutes()<10 ? "0" : "") + nDate.getMinutes();
var seconds = (nDate.getSeconds()<10 ? "0" : "") + nDate.getSeconds();
var timeString = hours + ":" + minutes + ":" + seconds;
document.getElementById("clock").innerText = timeString;
}
setInterval(updateTime, 1000);
It starts at 01:00 due to your timezone (UTC +1 CET Central European Time, Stockholm).
Create your date in the following manner:
const utcDate = new Date(Date.UTC(2019, 5, 11, 0, 0, 0)); // second param is the month-index, it start at 0, so 5 means june
console.log(utcDate);
Why don't use the unix timestamp, is really more simple and timezone free.
When user enter on the website
var d = new Date().getTime();
sessionStorage.setItem('time', d);
then
function updateTime(){
var nDate = new Date().getTime();
var startDate = sessionStorage.getItem('time');
var duration = nDate-startDate;
var seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
var timeString = hours + ":" + minutes + ":" + seconds;
document.getElementById("clock").innerText = timeString;
}
setInterval(updateTime, 1000);
recently i implemented a count timer for my shopping website that sets a limit of 24 hours when they create an order and not check out with a payment,so that counter reminds him/her that have to make a payment. The timer that is in our table is the start time and is adjusted by the current time up to 24 hours - after that, the order is cancelled.
Now i have a problem, when i reload the page the counter restarts from 24 hours this is my code
<script type="text/javascript">
function startTimer(duration, display) {
var start = '<?php echo $pending_order_date;?>';
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;
if(minutes >= 60){
hours = (minutes / 60) | 0;
minutes = (minutes % 60) | 0;
}else{
hours = 0;
}
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + 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 twentyfourhour = 60 * 60 *24,
display = document.querySelector('#time');
startTimer(twentyfourhour, display);
};
</script>
Please see my code, i get the timestamp in php from my table and the count.
Your help would be appreciated.
You need to store your left off duration somewhere. localStorage seems to be better fit
function startTimer(duration, display) {
var start = '<?php echo $pending_order_date;?>';
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;
if(minutes >= 60){
hours = (minutes / 60) | 0;
minutes = (minutes % 60) | 0;
}else{
hours = 0;
}
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + 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;
}
localStorage.setItem('timer', diff);
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var twentyfourhour = 60 * 60 *24,
display = document.querySelector('#time');
var timePassed = localStorage.getItem('timer');
startTimer((typeof timer!=='undefined' ? timer : twentyfourhour), display);
};
so each time your duration changes, it will update localStorage timer value. when you reload page, it will look for timer item in localStorage and will get that value, if it doesn't exist then will use 24 hrs. you may also add a controller to remove timer once it is expired, and store it with the order number or something so you can use multiple values. but this should give you an idea.
I am writing for web exam page ,in there I have to set 30 minutes to exam time.So I used onload and settimeout function to check if 30 minutes over,the question page is close and go to finish page.I want to add current minutes 30.But it's doesn't work,don't go to finish.php.!
<body onload="time()">
<!-- question code -->
<div id="time"></div><!-- show time -->
</body>
JS
<script>
function time(){
var j = new Date();
var hr = j.getHours();
var sec = j.getSeconds();
var min = j.getMinutes();
var m = min + 30;//set 30 minutes exam times
if (m === min) {
location.href = "finish.php";
}
document.getElementById('time').innerHTML = hr + ":" + min + ":" + sec;
setTimeout(function() {
time()
}, 1000);
}
</script>
Try with this
function time(){
setTimeout(function() {
location.href = "finish.php";
}, 30*60*1000);
setInterval(function() {
var j = new Date();
var hr = j.getHours();
var min = j.getMinutes();
var sec = j.getSeconds();
document.getElementById('time').innerHTML = hr + ":" + min + ":" + sec;
}, 1000);
}
function time() {
var time = 60 * 1; //Replace 1 with 30 minutes
var minutes, seconds;
setInterval(function () {
minutes = parseInt(time / 60)
seconds = parseInt(time % 60);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById('time').innerHTML = minutes + ":" + seconds;
time--;
if (time < 0) {
location.href = "finish.php";
}
}, 1000);
}
<body onload="time()">
<!-- question code -->
<div id="time"></div><!-- show time -->
</body>
Your are assigning new value to m every timeout. you should initialize, m only once.
also minute goes from 0-59 so you cant always check for it is equal to m + 30, thats wrong way of doing it
being said that its always better to do this timeout at server side, at client side there are enough ways to cheat around it
I have a timer countdown which displays in a <span>, I need it to output into a readonly <input> instead so I can calculate with the value. Is there any way to change this?
I tried
document.getElementById("timedown").value = display;
I tried various other things which just got messy and didn't work. Below is the function and the input
function startTimer(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) {
// faaopoopo se tasi sekone
start = Date.now() + 1000;
}
};
// amata vave
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 10,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
<div class="transtime">
<form>
<input type="text" id="timedown" value="0" readonly/>
</form>
</div>
Change
display.textContent = minutes + ":" + seconds;
to
document.getElementById("timedown").value = minutes + ":" + seconds;
or change
display = document.querySelector('#timedown');
and
display.value = minutes + ":" + seconds;
Here is a working codepen
Change the function to this:
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.value= minutes + ":" + seconds;
if (diff <= 0) {
// faaopoopo se tasi sekone
start = Date.now() + 1000;
}
};
changing the value instead of the text value and it should work
I'm making a html5 video player and am using javascript to update the current time out of the total time. So far my script is
function updateTime() {
var curTime = mediaPlayer.currentTime;
var totTime = mediaPlayer.duration;
timePlayed.innerHTML = curTime + '/' + totTime;
}
I have an eventlistener at the start. So the script works, but it outputs it like 23.703/285.067513 How would I get it to output something like 00:00 / 00:00 Just like the youtube video player, so it would be like minute minute:second second / minute minute:second second. For my html, I just have a span <span id="timePlayed">00:00/00:00</span>
If anyone can help me with this, thanks in advance!
I think, you can use an another function for it.Look what I found.
function formatSeconds(seconds) {
var date = new Date(1970,0,1);
date.setSeconds(seconds);
return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1"); }
https://stackoverflow.com/a/17781037/2500784
You can do the following and solve your issues
video.addEventListener("timeupdate", function() {
function formatTime(seconds) {
var minutes = Math.floor(seconds / 60);
minutes = (minutes >= 10) ? minutes : minutes;
var hours = Math.floor(minutes / 60);
hours = (minutes >= 10) ? hours : hours;
var seconds = Math.floor(seconds % 60);
seconds = (seconds >= 10) ? seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
var seconds = video.currentTime;
currentTime.innerHTML = formatTime(seconds);
});
video.addEventListener("timeupdate", function() {
function formatTime(seconds) {
var minutes = Math.floor(seconds / 60);
minutes = (minutes >= 10) ? minutes : minutes;
var seconds = Math.floor(seconds % 60);
seconds = (seconds >= 10) ? seconds : seconds;
return minutes + ":" + seconds;
}
var seconds = video.duration;
durationTime.innerHTML = formatTime(seconds);
});
Then you must have this HTML Markup as defined
<span id="currentTime">00:00:00</span> / <span id="durationTime">00:00:00</span>