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();
Related
I tried to display timer on webpage in label (label id is MsgTimer) using following function. But when the function is called the 2/more times then 2/ more timers are displayed and it won't reset the timer but overload the label text and display multiple timers on a lable. I want to reset the label text each time the function is called.
function startTimer() {
var x;
clearInterval(x);
document.getElementById("MsgTimer").innerHTML = "";
// Here I was supposed to fetch the SessionTimeout data from appsettings.json
// But for now I entered data manually for 15 minutes
var countDownDate = new Date().getTime() + 900000;
// Update the count down every 1 second
x = setInterval(function () {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(distance / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// add a zero in front of numbers<10
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
hours = checkTime(hours);
minutes = checkTime(minutes);
seconds = checkTime(seconds);
// Display the result in the element with id="lblTime"
document.getElementById("MsgTimer").innerHTML = "";
document.getElementById("MsgTimer").innerHTML = "Session Expires In" + " " + minutes + " : " + seconds + "";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("MsgTimer").innerHTML = "SESSION EXPIRED";
window.alert("Session Timeout");
}
}, 1000);
}
startTimer();
The problem with your code might be the var x; declaration, because variables declared using var keywords, are actually function scoped.
So, every time startTimer(); is called it is creating a new x variable within the function scope only and because of that the clearInterval(x) cannot clear the previous interval because it cannot access the previous value of x from previous startTimer(); call.
Try moving your var x; declaration outside the function and see if it works.
Updated [Working]:
/* Timer - Display Session Timeout */
var x = 0;
function startTimer() {
var countDownDate = (new Date().getTime()) + ((parseInt(#SessionTimer)) * 60000);
clearInterval(x);
x = setInterval(function () {
var now = new Date().getTime();
var distance = countDownDate - now;
var hours = Math.floor(distance / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
hours = checkTime(hours);
minutes = checkTime(minutes);
seconds = checkTime(seconds);
document.getElementById("MsgTimer").innerHTML = "Session Expires In" + " " + hours + " : " + minutes + " : " + seconds + "";
if (distance < 0) {
clearInterval(x);
document.getElementById("MsgTimer").innerHTML = "SESSION EXPIRED";
window.alert("Session Timeout");
}
}, 1000);
}
startTimer();
Alternative [JQuery]:
/* Show 15 Minutes Timer */
var timer2 = "15:01";
var interval = setInterval(function () {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
//minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html('Session Expires In' + ' ' + minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
}, 1000);
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 was just wondering with this, how can I get it to display only seconds when minutes hit zero?
So instead of displaying "0 minutes and 41 seconds"
I would like it to only display "41 seconds"
Is this possible?
<script type="text/javascript">
var count = <? = $time['timefromdb'] ?>;
var now = Math.floor(new Date().getTime() / 1000);
count = count - now;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
minutes %= 60;
hours %= 24;
document.getElementById("clock").innerHTML = minutes + " minutes and " + seconds + " seconds";
}
</script>
Simplest would be
document.getElementById("clock").innerHTML = (minutes?minutes+ " minutes and ":"")+ seconds + " seconds";
Try this
<script type="text/javascript">
var count = <?= $time['timefromdb'] ?>;
var now = Math.floor(new Date().getTime() / 1000);
count = count - now;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer()
{
count = count - 1;
if(count == -1)
{
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
minutes %= 60;
hours %= 24;
if (minutes > 0) {
min = minutes + " minutes and ";
}
else {
min = "";
}
document.getElementById("clock").innerHTML = min + seconds + " seconds";
}
</script>
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>
I have an requirement to create a timer in that will show up in the alertbox of javascript and it will start counting back from 4 minutes to 0.. The moment time is over , it should stop the timer. Everything I want this to be created in Javascript. I have tried with following code that I got from this link:
Timer in Javascript
But it is not working with me. I have done this::
<script>
window.onload = CreateTimer("timer", 30);
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if (TotalSeconds <= 0) {
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : +Time;
}
</script>
<div class="page">
<div id='timer' style="float: left; width: 50%; background-color: red; color: white;"></div>
</div>
I hope, it will help you.
window.onload = CreateTimer("timer", 30);
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout(Tick, 1000); // remove double quote
}
function Tick() {
if (TotalSeconds <= 0) {
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout(Tick, 1000); // remove double quote
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : +Time;
}
Comments are there where I had done changes. Also you need to modify your code as per requirement as alert message is display after every moment when seconds equal to 0 whether time is remaining. I didn't know your requirement about this I didn't touch that code.
Please follow this link for live demo.