Multiuse and reusable JavaScript countdown timer - javascript

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();
}
};
})

Related

Add milliseconds to JavaScript

I created a simple game for which I need a countdown. Now everything is fine, but I need to add a millisecond to the timer. I used the code found on the internet, but it lacks just those milliseconds. My attempts have not been successful, so I am asking you for help.
var seconds;
var temp;
function countdown() {
time = document.getElementById('countdown').innerHTML;
timeArray = time.split(':')
seconds = timeToSeconds(timeArray);
if (seconds == '') {
temp = document.getElementById('countdown');
temp.innerHTML = '00:00:00';
return;
}
seconds--;
temp = document.getElementById('countdown');
temp.innerHTML = secondsToTime(seconds);
timeoutMyOswego = setTimeout(countdown, 1000);
}
function timeToSeconds(timeArray) {
var minutes = (timeArray[0] * 1);
var seconds = (minutes * 60) + (timeArray[1] * 1);
return seconds;
}
function secondsToTime(secs) {
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
minutes = minutes < 10 ? '0' + minutes : minutes;
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
seconds = seconds < 10 ? '0' + seconds : seconds;
return minutes + ':' + seconds;
}
countdown();

countdown timer is not working javascript

I m trying to run this countdown timer but it's not working please help me
I try to generate a random number between two numbers and start timer but it's working please help me
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second parm
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
var count = getRandomArbitrary(21000,23000);
var counter = setInterval(timer, 1000);
function timer() {
console.log(count);
if (parseInt(count) <= 0) {
clearInterval(counter);
return;
}
var temp = count.toHHMMSS();
count = (parseInt(count) - 1).toString();
$('#timer').html(temp);
}
HTML code
<div id="timer"></div>
You have extended the string prototype with your conversion function, but you're not using a string (count is a number from the getRandom... method). Use a normal function instead, and it will work on more types:
toHHMMSS = function (str) {
var sec_num = parseInt(str, 10); // don't forget the second parm
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
var count = getRandomArbitrary(21000,23000);
var counter = setInterval(timer, 1000);
function timer() {
console.log(count);
if (parseInt(count) <= 0) {
clearInterval(counter);
return;
}
var temp = toHHMMSS(count);
count = (parseInt(count) - 1).toString();
$('#timer').html(temp);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer"></div>
Try my code.
Your code problem is that you didn't convert count.toHHMMSS(); this line into string when you call.
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second parm
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
var count = getRandomArbitrary(21000,23000);
var counter = setInterval(timer, 1000);
function timer() {
console.log(count);
if (parseInt(count) <= 0) {
clearInterval(counter);
return;
}
var temp = count.toString().toHHMMSS();
count = (parseInt(count) - 1).toString();
$('#timer').html(temp);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<div id="timer"></div>

Js code always runs even i don't hit the button

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.

How can I use an Ajax response value for timer?

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>

Display hours in countdown timer javascript

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>

Categories

Resources