I somehow copied this code from stackoverflow, but I forgot the link. I noticed that if I try to input hours, this will be converted into minutes which is very odd to look.
var hms = "02:30:00";
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
if(seconds > 0)
{
function secondPassed() {
var minutes = Math.round((seconds - 30)/60),
remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = ":" +minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
//form1 is your form name
document.form_quiz.submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
}
time{
color:red;
}
02:30:00 <br>
<time id="countdown">02:30:00</time>
The countdown should display like 02:29:59 after ( 1 second passes ). and not 149:59.
You have forget to calculate hour time.
Try like this ==>
var hms = "02:30:00";
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
if(seconds > 0)
{
function secondPassed() {
var minutes = Math.round((seconds - 30)/60),
remainingSeconds = seconds % 60;
var hour =Math.floor((minutes)/60);
minutes = minutes%60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
hour = ("0" + hour).slice(-2);
minutes = ("0" + minutes).slice(-2);
remainingSeconds= ("0" + remainingSeconds).slice(-2);
document.getElementById('countdown').innerHTML = hour +":" +minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
//form1 is your form name
document.form_quiz.submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
}
time{
color:red;
}
02:30:00 <br>
<time id="countdown">02:30:00</time>
Related
I am trying to create a countdown timer that can be used for an infinate number of uses on a page, and one I can reuse just by add a class to a span called 'timer'.
I have the following countdown timer which works a treat, but I have to copy the code of the timer for every timer I need (which isn't great programming) and makes it impossible to reuse as much times as I need.
<script>
$(document).ready(function() {
timer();
function timer() {
var endTime = "<?php echo $planet->constructionarray[$i]['end_time']; ?>";
var timeInSeconds = Math.floor(Date.now() / 1000);
var timeRemaining = endTime - timeInSeconds;
var hours = Math.floor(timeRemaining / 3600);
var minutes = Math.floor((timeRemaining - (hours * 3600)) / 60);
var seconds = timeRemaining - (hours * 3600) - (minutes * 60);
if(seconds < 10) { seconds = "0" + seconds; } else { seconds = seconds; }
if(minutes < 10) { minutes = "0" + minutes; } else { minutes = minutes; }
if(hours < 10) { hours = "0" + hours; } else { hours = hours; }
$("#timer<?php echo $i; ?>").text(hours + ":" + minutes + ":" + seconds);
if(endTime <= timeInSeconds) { clearInterval(interval); location.reload(); }
};
interval = setInterval(timer, 1000);
})(jQuery);
</script>
I have tried creating a new timer with the following code, this works, but only works on the first span on the page.
<span id="countdown_timer_sm" endtime="1567425139">TIMERTEST</span><br/>
<span id="countdown_timer_sm" endtime="1567425139">TIMERTEST</span><br/>
<span id="countdown_timer_sm" endtime="1567425139">TIMERTEST</span><br/>
<span id="countdown_timer_sm" endtime="1567925139">TIMERTEST</span>
$(document).ready(function() {
timer();
function timer() {
var endTime = document.getElementById('countdown_timer_sm').getAttribute("endtime");
var timeInSeconds = Math.floor(Date.now() / 1000);
var timeRemaining = endTime - timeInSeconds;
var hours = Math.floor(timeRemaining / 3600);
var minutes = Math.floor((timeRemaining - (hours * 3600)) / 60);
var seconds = timeRemaining - (hours * 3600) - (minutes * 60);
if(seconds < 10) { seconds = "0" + seconds; } else { seconds = seconds; }
if(minutes < 10) { minutes = "0" + minutes; } else { minutes = minutes; }
if(hours < 10) { hours = "0" + hours; } else { hours = hours; }
document.getElementById('countdown_timer_sm').innerHTML = (hours + ":" + minutes + ":" + seconds);
if(endTime <= timeInSeconds) { clearInterval(interval); location.reload(); }
};
interval = setInterval(timer, 1000);
})(jQuery);
Could anyone give me some guidance please?
I hope it helps.
I used Jquery and class instead of ids.
Note you can't use the same ids and it only rendered only 1 id.
<span class="countdown_timer_sm" endtime="4567425139">TIMERTEST</span><br/>
<span class="countdown_timer_sm" endtime="1567425139">TIMERTEST</span><br/>
<span class="countdown_timer_sm" endtime="3567425139">TIMERTEST</span><br/>
<span class="countdown_timer_sm" endtime="2567425139">TIMERTEST</span>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
$(function(){
$('.countdown_timer_sm').each(function(){
$endTime = $(this).attr('endtime');
$span = $(this);
interval($endTime,$span);
});
function interval($endTime,$span){
setInterval(
function(){
timer($endTime, $span);
}, 1000);
}
function timer($endTime, $thisSpan){
var timeInSeconds = Math.floor(Date.now() / 1000);
var timeRemaining = $endTime - timeInSeconds;
var hours = Math.floor(timeRemaining / 3600);
var minutes = Math.floor((timeRemaining - (hours * 3600)) / 60);
var seconds = timeRemaining - (hours * 3600) - (minutes * 60);
if(seconds < 10) { seconds = "0" + seconds; } else { seconds = seconds; }
if(minutes < 10) { minutes = "0" + minutes; } else { minutes = minutes; }
if(hours < 10) { hours = "0" + hours; } else { hours = hours; }
//console.log($thisSpan);
$thisSpan.html(hours + ":" + minutes + ":" + seconds);
if($endTime <= timeInSeconds) {
clearInterval(); location.reload();
}
};
})
<script>
window.setInterval(function(){ document.title = "site - " + msToTime();}, 1000);
function msToTime() {
var milliseconds = parseInt((remainingTime % 1000) / 100),
seconds = parseInt((remainingTime / 1000) % 60),
minutes = parseInt((remainingTime / (1000 * 60)) % 60),
hours = parseInt((remainingTime / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
</script>
remainingTime would bring however much seconds left in the timer (00:07:19.7). When I change document.title to alert(), it would successfully give alerts every second, but I want the tab title to update every second. How would I accomplish this?
Here you go! That's what you wanted? I edited your code adding the functionality of time, test it! changing every millisecond.
P.S - If i were you i would delete the milliseconds. Stays more clean without it
window.setInterval(function(){ document.title = "rumseytime - " + msToTime();}, 1000);
function msToTime() {
var remainingTime = new Date();
var milliseconds = remainingTime.getMilliseconds();
seconds = remainingTime.getSeconds();
minutes = remainingTime.getMinutes();
hours = remainingTime.getHours();
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
I have a js code and I wanna run it when I click the button.It's seems ok to me but it's run even i don't hit the button.
Probably it has a simple answer but I couldn't handle it.I'm new....
var upgradeTime = 600;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML =
days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Tamamlandı.";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
<span id="countdown" class="timer"></span>
<input id="" type="button" value="clickme" onclick="timer();" />
You need to remove var countdownTimer = setInterval('timer()', 1000);
outside the function:
You can include all your core logic to a new function coreTimer()
Call coreTimer() from timer()
make sure countdownTimer is declared in global scope so that it can be cleared using clearInterval inside coreTimer() function.
var upgradeTime = 10;
var seconds = upgradeTime;
var countdownTimer;
function timer() {
countdownTimer = setInterval('coreTimer()', 1000);
}
function coreTimer() {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Tamamlandı.";
} else {
seconds--;
}
}
<span id="countdown" class="timer"></span>
<input id="" type="button" value="clickme" onclick="timer();" />
setInterval method calls a function or evaluates an expression at specified intervals. So the statement
var countdownTimer = setInterval('timer()', 1000);
will execute your timer function every 1000 milliseconds. Hence your function is getting called even when you are not clicking the button. You need to modify that statement accordingly or remove it completely.
I want to make a timer that gets its value from an Ajax call. Here is my code:
function timer(seconds) {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + "tundi " + minutes + "minutit " + remainingSeconds+ "sekundit";
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
console.log(seconds);
}
var countdownTimer = setInterval('timer()', 1000);
}
$.ajax({
type: "GET",
url: "AjaxHandler.php",
dataType: "JSON",
data:{action:"gym"},
success: function(result){
timer(result); // receiving php strtotime(), value something like 150000
},
error:function(){
console.log("Error: Unknown Error")
}
});
Now the problem is that I can't get the value for countdownTimer outside of the scope, so I placed the countdownTimer inside function. But that's not working and I knew that.
Is declaring the seconds value to html object going to work? Like $("#test").val(response)
So my question is: how Can I make this timer work?
Following example demonstrate how you can use a callback function to solve your problem.
function timer(seconds, countdownTimer, callback) {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + "tundi " + minutes + "minutit " + remainingSeconds + "sekundit";
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
console.log(seconds);
}
//Pass seconds param back to the caller.
callback(seconds);
}
//Inside the ajax success function you should call following code snippet instead of calling timer(30).
//We pass the countdownTimer param into the timer function as well.
var countdownTimer = null,
seconds = 30;
countdownTimer = setInterval(function() {
timer(seconds, countdownTimer, function(_seconds){
seconds = _seconds;
})
}, 1000);
<div id="countdown"></div>
Well it does not work becuase you call timer() without the seconds in the setTimeout. So you need to pass it.
function timer(seconds)
{
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + "tundi " + minutes + "minutit " + remainingSeconds+ "sekundit";
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
console.log(seconds);
setTimeout(timer, 1000, seconds);
}
}
timer(30);
<div id="countdown"></div>
But as an FYI, setTimeout is not accurate so the time it ends will be off. So what can you do? Set a date and subtract the current time from it.
function startTimer(seconds) {
var endTime = new Date();
endTime.setSeconds(endTime.getSeconds() + seconds);
timer();
function timer() {
var seconds = Math.ceil((endTime - new Date()) / 1000)
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + "tundi " + minutes + "minutit " + remainingSeconds + "sekundit";
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
console.log(seconds);
setTimeout(timer, 1000);
}
}
}
startTimer(30);
<div id="countdown"></div>
I'm new in javascript.
My PHP script returns a value in this format
d:h:m:s
Now I would like to have a countdown which is able to countdown each second from this.
I modified a countdown. This works once a time, after the countdown "ticks" each second it returns NaN all the time. Any idea what I do wrong?
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
var days = Math.floor(timestamp / 86400);
console.log(time,timestamp);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - hours * 3600) / 60);
var seconds = timestamp - ((days * 86400) + (hours * 3600) + (minutes * 60))-1;
$(this).data("time",""+days+":"+hours+":"+minutes+":"+seconds);
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>
As far as I can see you have 2 problems here:
after the first execution you change the pattern of the text you display in the h1. First you have 02:03:05:59. Then you want to write 02 days 03:05:58 into the tag. Next time you parse it, you get the error because you split at : and that does not work anymore as you have days instead of : as the seperator for the first part.
When calculating the minutes, you should also substract the days and not just the hours.
When you wan to keep the dd:hh:mm:ss format, you could do it like this:
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).text().split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
timestamp -= timestamp > 0;
var days = Math.floor(timestamp / 86400);
console.log(days);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - days * 86400 - hours * 3600) / 60);
var seconds = timestamp - days * 86400 - hours * 3600 - minutes * 60;
if (days < 10) {
days = '0' + days;
}
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>
Your snippet goes from dd:hh:mm:ss to dd days, hh hours. So second time around, your tag contains non-parsable text.
I have changed it to something more precise. Something even MORE precise would be to give a timestamp in milliseconds in the future instead of something with seconds since it will take several seconds to render the page. If you round on minutes from the server, it would likely be better.
var aDay = 24*60*60*1000, anHour = 60*60*1000, aMin = 60*1000, aSec = 1000;
$(document).ready(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var date = new Date();
date.setDate(date.getDate()+parseInt(time[0],10))
date.setHours(date.getHours()+parseInt(time[1],10),date.getMinutes()+parseInt(time[2],10),date.getSeconds()+parseInt(time[3],10),0)
$(this).data("when",date.getTime());
});
setInterval(function() {
$('.countdown').each(function() {
var diff = new Date(+$(this).data("when"))-new Date().getTime();
var seconds, minutes, hours, days, x = diff / 1000;
seconds = Math.floor(x%60); x=(x/60|0); minutes = x % 60; x= (x/60|0); hours = x % 24; x=(x/24|0); days = x;
$(this).text(
days + ' day' +(days==1?", ":"s, ") +
hours + ' hour' +(hours==1?", ":"s, ") +
minutes + ' minute'+(minutes==1?", ":"s, ") +
seconds + ' second'+(seconds==1?".":"s.")
);
});
}, 500);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown" data-time="02:03:05:59"></h1>