<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;
}
Related
I have a function that converts ms to s and m and it will display as 0:00 but i want it to display it as 0:00.0. How would i do this?
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return (seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds);
}
console.log(
millisToMinutesAndSeconds(123456)
)
set toFixed() with the desired number of digits:
var seconds = ((millis % 60000) / 1000).toFixed(1);
sorry, I do not know where you got the code from, the code may look something like this. I suggest you close this question.
function millisToMinutesAndSeconds(millis) {
const minutes = Math.floor(millis / 60000);
const seconds = Math.floor((millis - (minutes * 60000))/ 1000);
const milliseconds = (millis - (minutes * 60000) - (seconds * 1000));
const mins = minutes < 10 ? "0" + minutes : "" + minutes;
const secs = seconds < 10 ? "0" + seconds : "" + seconds;
const msecs = milliseconds < 10 ? "00" + milliseconds : milliseconds < 100 ? "0" + milliseconds : "" + milliseconds;
return `${mins}:${secs}.${msecs}`;
}
console.log(
millisToMinutesAndSeconds(123456)
)
I am building an Angular 9 app. In this app I got a stopwatch component that counts up. This works perfectly fine but I need it to be double digits.
Right now the output is:
0:0:9
I need it to be
00:00:09
This is the method that takes care of the output.
timeDifference() {
const currentTime = moment().valueOf();
const startTime = moment(this.form.get('starts_at').value).valueOf();
const difference = currentTime - startTime;
let hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((difference % (1000 * 60)) / 1000);
hours = (hours < 10) ? 0 + hours : hours;
minutes = (minutes < 10) ? 0 + minutes : minutes;
seconds = (seconds < 10) ? 0 + seconds : seconds;
this.pastTime = hours + ':' + minutes + ':' + seconds;
}
What can I do to fix this?
Thank you!
Your code with Zero concatenated as string.
let hours = 9;
let minutes = 6;
let seconds = 30;
hours = (hours < 10) ? '0' + hours : hours;
minutes = (minutes < 10) ? '0' + minutes : minutes;
seconds = (seconds < 10) ? '0' + seconds : seconds;
console.log(hours + ':' + minutes + ':' + seconds);
padStart() as mentioned by #mark-baijens
let hours = 9;
let minutes = 6;
let seconds = 30;
console.log(hours.toString().padStart(2, '00') + ':' + minutes.toString().padStart(2, '00') + ':' + seconds.toString().padStart(2, '00'));
If you're already using moment why reinvent the wheel? You can just use moment's "format()" function to get the desired output. Or even using the native Date object's "toLocaleTimeString".
You can see both in action in this snippet:
setInterval(() => {
document.getElementById("localeDiv").innerHTML = new Date().toLocaleTimeString();
document.getElementById("momentDiv").innerHTML = moment().format("HH:mm:ss");
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<h4>With Date.toLocaleTimeString()</h4>
<div id="localeDiv"></div>
<h4>With moment</h4>
<div id="momentDiv"></div>
Since you are calculating a string, you could directly format the value.
this.pastTime = `${hours < 10 ? '0' : ''}${hours}:${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}:`
Alternatively, a more cleaner approach would be to store hours, minutes and seconds in three separate fields accessible from the template and format it in the template itself via custom pipe. Assuming you have the three variables available in the template, you could write a pipe like following:
#Pipe({
name: 'doubledigit'
})
export class DoubleDigitPipe implements PipeTransform {
transform(value: number, ...args: unknown[]): string {
return `${value < 10 ? '0' : ''}${value}`;
}
}
and in the template where you want to show it
{{ hours | doubledigit }}:{{ minutes | doubledigit }}:{{ seconds | doubledigit }}
let hours = 2;
let minutes = 3;
let seconds = 20;
function n(n){
return n > 9 ? "" + n: "0" + n;
}
console.log(n(hours) + ':' + n(minutes) + ':' + n(seconds));
I have created my own countdown and it seems that I'm missing a part, whenever I refresh the page it also refresh the timer itself. I am looking to maximize the performance with that script so how can I make it looping infinitely?
Here is the code:
function startGRBTimer(duration, display) {
var timer = duration,
hours, minutes, seconds;
setInterval(function() {
days = parseInt(timer / (24 * 60 * 60), 10);
hours = parseInt(timer % (24 * 60 * 60) / (60 * 60), 10);
minutes = parseInt(timer % (60 * 60) / 60, 10);
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = days + "d" + " " + hours + "h " + minutes + "m " + seconds + "s";
--timer;
if (timer <= 0) {
timer = duration;
}
}, 1000);
}
var display = document.querySelector("#grb");
startGRBTimer(60, display);
That's just the way this code works, there is nothing wrong with it. Every time you refresh the page, the script gets re-run, and the var timer = duration, hours, minutes, seconds; is created whenever the page is loaded.
You should look into creating first, and then storing the variable to the user's local storage, and have your program read the info from that variable (or array).
You need to do some job independently from your web application, with ability to live after page refresh, right?
It's highly likely that ServiceWorkers will be useful for you.
We could "misuse" window.name (see documentation link) for this case like in following example. Or you could use localStorage, but this does not work for local files (file:///...). And because of this window.name is better and shorter too.
Solution
function startGRBTimer(duration, display)
{
var timer = window.name == '' ? duration : window.name,
hours, minutes, seconds;
setInterval(function()
{
days = parseInt(timer / (24 * 60 * 60), 10);
hours = parseInt(timer % (24 * 60 * 60) / (60 * 60), 10);
minutes = parseInt(timer % (60 * 60) / 60, 10);
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = days + "d" + " " + hours + "h " + minutes + "m " + seconds + "s";
--timer;
if(timer <= 0)
{
timer = duration;
}
window.name = timer;
}, 1000);
}
var display = document.querySelector("#grb");
startGRBTimer(60, display);
<div id="grb"></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>
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>