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>
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();
}
};
})
I just can't figure why this doesn't work for some odd values.
For example when trying to convert 22.68 to hours and minutes the output is 22:40.800000000000004 (Seconds shouldn't even appear)
if (str_HR_PER_WEEK.indexOf('.') > -1)
{
var str_HR_PER_WEEK_hrs = str_HR_PER_WEEK.substring(0 , str_HR_PER_WEEK.indexOf('.'));
var str_HR_PER_WEEK_mins = str_HR_PER_WEEK.substring(str_HR_PER_WEEK.indexOf('.') + 1);
var float_HR_PER_WEEK_mins = parseFloat("0." + (str_HR_PER_WEEK_mins), 10);
var float_HR_PER_WEEK_mins_actual = float_HR_PER_WEEK_mins * 60;
float_HR_PER_WEEK_mins_actual = float_HR_PER_WEEK_mins_actual.toString();
tables.CURRENT_EMPLOYEES.HOURS_PER_WEEK.value = getTwoDigitTime(str_HR_PER_WEEK_hrs) + ":" + getTwoDigitTime(float_HR_PER_WEEK_mins_actual);
}
else
{
tables.CURRENT_EMPLOYEES.HOURS_PER_WEEK.value = str_HR_PER_WEEK;
}
You have to ways to achieve that,
one, do the calculations yourself:
var decimalTimeString = "1.6578";
var decimalTime = parseFloat(decimalTimeString);
decimalTime = decimalTime * 60 * 60;
var hours = Math.floor((decimalTime / (60 * 60)));
decimalTime = decimalTime - (hours * 60 * 60);
var minutes = Math.floor((decimalTime / 60));
decimalTime = decimalTime - (minutes * 60);
var seconds = Math.round(decimalTime);
if(hours < 10)
{
hours = "0" + hours;
}
if(minutes < 10)
{
minutes = "0" + minutes;
}
if(seconds < 10)
{
seconds = "0" + seconds;
}
alert("" + hours + ":" + minutes + ":" + seconds);
Two, use built in function to convert to string and then to hh:mm:
var decimalTimeString = "1.6578";
var n = new Date(0,0);
n.setSeconds(+decimalTimeString * 60 * 60);
n.setMinutes(+decimalTimeString * 60);
var result = n.toTimeString().slice(0, 5);
document.write(result);
I've got a neat function to do just that:
function hoursToHHMM(hours) {
var h = String(Math.trunc(hours)).padStart(2, '0');
var m = String(Math.abs(Math.round((hours - h) * 60))).padStart(2, '0');
return h + ':' + m;
}
It handles negative values as a bonus.
Usage is trivial:
var hours = -7.33333;
console.log(hoursToHHMM(hours));
Results in: -07:20
You can play with it here: https://jsfiddle.net/r150c2me/
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>
var currentTime = audio.currentTime | 0;
var duration = audio.duration | 0;
it works but,
it shows the audio's total length and current time in only second format
i want to convert the default second value in Minute:Second format
Try this (lightly tested):
var seconds = currentTime % 60;
var foo = currentTime - seconds;
var minutes = foo / 60;
if(seconds < 10){
seconds = "0" + seconds.toString();
}
var fixedCurrentTime = minutes + ":" + seconds;
var currentTime = audio.currentTime | 0;
var duration = audio.duration | 0;
var minutes = "0" + Math.floor(duration / 60);
var seconds = "0" + (duration - minutes * 60);
var dur = minutes.substr(-2) + ":" + seconds.substr(-2);
var minutes = "0" + Math.floor(currentTime / 60);
var seconds = "0" + (currentTime - minutes * 60);
var cur = minutes.substr(-2) + ":" + seconds.substr(-2);
You can simply write the code yourself; it's not as if it's complicated or would ever change:
function pad(num, size) {
var s = num + '';
while (s.length < size) {
s = '0' + s;
}
return s;
}
function format_seconds(secs) {
return Math.floor(secs / 60) + ':' + (pad(secs % 60, 2));
}
dropping my own answer after 5 years and 9 months.
function() {
if(this.myAudio.readyState > 0) {
var currentTime = this.myAudio.currentTime;
var duration = this.myAudio.duration;
var seconds: any = Math.floor(duration % 60);
var foo = duration - seconds;
var min: any = foo / 60;
var minutes: any = Math.floor(min % 60);
var hours: any = Math.floor(min / 60);
if(seconds < 10){
seconds = "0" + seconds.toString();
}
if(hours > 0){
this.audioDuration = hours + ":" + minutes + ":" + seconds;
} else {
this.audioDuration = minutes + ":" + seconds;
}
}
}
I used typescript, hope this helps...
I want to countdown timer in format of hh:mm:ss so I use this code it's convert seconds into required format but when I count down it display me NaN. Can you tell me what I am doing wrong
Here is code
<div id="timer"></div>
JS
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;
}
var count = '62';
count = count.toHHMMSS();
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count <= 0) {
clearInterval(counter);
return;
}
$('#timer').html(count);
}
Here is JsFiddle link CountDown Timer
Well, let's take a look at what your code does:
Set count to the string value 62.
Convert it to HHMMSS, so now count is equal to the string 00:01:02
Start the timer.
On the first run of the timer, decrement count. Erm... count is a string, you can't decrement it. The result is not a number.
Okay, so with that out of the, way how about fixing it:
function formatTime(seconds) {
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60,
s = seconds % 60;
if (h < 10) h = "0" + h;
if (m < 10) m = "0" + m;
if (s < 10) s = "0" + s;
return h + ":" + m + ":" + s;
}
var count = 62;
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count < 0) return clearInterval(counter);
document.getElementById('timer').innerHTML = formatTime(count);
}
var count = '62'; // it's 00:01:02
var counter = setInterval(timer, 1000);
function timer() {
if (parseInt(count) <= 0) {
clearInterval(counter);
return;
}
var temp = count.toHHMMSS();
count = (parseInt(count) - 1).toString();
$('#timer').html(temp);
}
http://jsfiddle.net/5LWgN/17/
If you use the jquery moment plugin. If you are not using jQuery moment then you can use formatTime(seconds) function that is in the #Niet's answer https://stackoverflow.com/a/18506677/3184195
var start_time = 0;
var start_timer = null;
start_timer = setInterval(function() {
start_time++;
var formate_time = moment.utc(start_time * 1000).format('mm:ss');
$('#Duration').text(formate_time);
}, 1000);
});
function clear() {
if (start_timer) clearInterval(start_timer);
}