I finally managed to make my 24 hour non-date dependable countdown timer. The purpose of this is that the countdown starts every time someone visits the site. The problem is that when any unit (hours, mins, secs) reaches single digits values display them as such instead of the standard time format (9 minutes instead of 09 minutes, as it should). How can I implement a condition that if a value it's <= 9 it adds a 0 before it?
var count = 86400;
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);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + ":" + minutes + ":" + seconds; // watch for spelling
}
<span id='timer'></span>
Create one function similar to following that does the job for you:
function makeMeTwoDigits(n){
return (n < 10 ? "0" : "") + n;
}
And before printing your numbers call this function:
document.getElementById("timer").innerHTML = makeMeTwoDigits(hours) + ":" + makeMeTwoDigits(minutes) + ":" + makeMeTwoDigits(seconds);
Explanation:
Like #rfornal said, we're checking if the number is less that 10 which means single digit, add '0' and return otherwise add nothing and return.
One point to observe is this won't work if the number is negative.
You can use universal pad function from How to output integers with leading zeros in JavaScript
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
and change your code to:
document.getElementById("timer").innerHTML = pad(hours,2) + ":" + pad(minutes,2) + ":" + pad(seconds,2);
Try ...
document.getElementById("timer").innerHTML
= (hours<10 ? "0" + hours : hours) + ":"
+ (minutes<10 ? "0" + minutes : minutes) + ":"
+ (seconds<10 ? "0" + seconds : seconds);
Basically, saying if the value is less than 10, place a "0"; else just the value. Another way of saying this is if condition ? then : else ...
An alternate route ... more code would be:
var t_hours, t_minutes, t_seconds;
if (hours<10) {
t_hours = "0" + hours;
} else {
t_hours = hours;
}
if (minutes<10) {
t_minutes = "0" + minutes;
} else {
t_minutes = minutes;
}
if (seconds<10) {
t_seconds = "0" + seconds;
} else {
t_seconds = seconds;
}
document.getElementById("timer").innerHTML
= t_hours + ":" t_minutes + ":" t_seconds;
Related
I have data in json from laravel backend which looks like: "03:30:00", "01:45:00", "00:15:00"
Is there an easy way to count them together in vuejs so its looks like this: "05:30:00"
So this is simple javascript.
If the time string is always going to look the same, you can do:
let times = ["03:30:00", "01:45:00", "00:15:00"]; // you can have an unlimited number of time strings
let hours = 0;
let minutes = 0;
let seconds = 0;
for (const i in times) {
const time = times[i];
let splitTime = (time + "").split(":"); // make sure it's a string
seconds += parseInt(splitTime[2]);
if(seconds > 59){ // make sure it only goes until 59
minutes++;
seconds = seconds % 60;
}
minutes += parseInt(splitTime[1]);
if(minutes > 59){ // make sure it only goes until 59
hours++;
minutes = minutes % 60;
}
hours += parseInt(splitTime[0]);
}
let totalTime = (hours < 10 ? "0" + hours : hours) + ":"
+ (minutes < 10 ? "0" + minutes : minutes) + ":"
+ (seconds < 10 ? "0" + seconds : seconds); // put the left side zeros
I've been working on showing user's how long they spent on a certain page. I think I may have over complicated it. Currently I am showing them the number of minutes and then showing them the number of seconds. This almost works except when its at two minutes 5 seconds for example it looks like this: 2:5 instead of 2:05. Then once it hits 10 seconds its fine: 2:10.
Any idea how I'd change my code to correct this? Thanks!
var timer;
var timerStart;
var timeSpentOnSite = getTimeSpentOnSite();
function getTimeSpentOnSite(){
timeSpentOnSite = parseInt(localStorage.getItem('timeSpentOnSite'));
timeSpentOnSite = isNaN(timeSpentOnSite) ? 0 : timeSpentOnSite;
return timeSpentOnSite;
}
function startCounting(){
timerStart = Date.now();
timer = setInterval(function(){
timeSpentOnSite = getTimeSpentOnSite()+(Date.now()-timerStart);
localStorage.setItem('timeSpentOnSite',timeSpentOnSite);
timerStart = parseInt(Date.now());
// Convert to seconds
$("#timeSpentMin").html(parseInt(timeSpentOnSite/1000 / 60));
$("#timeSpentSec").html(parseInt(timeSpentOnSite/1000 % 60));
},1000);
}
startCounting();
You can use this simple function:
function padTime(time) {
return ("0" + time).slice(-2);
}
Pass it any time portion you want and it will pad it for you:
var min = 5;
var sec = 2;
console.log("Unpadded: " + min + ":" + sec);
console.log("Padded seconds: " + min + ":" + padTime(sec));
console.log("Padded minutes & seconds: " + padTime(min) + ":" + padTime(sec));
min = 12;
sec = 52;
console.log("Unpadded: " + min + ":" + sec);
console.log("Padded seconds: " + min + ":" + padTime(sec));
console.log("Padded minutes & seconds: " + padTime(min) + ":" + padTime(sec));
function padTime(time) {
return ("0" + time).slice(-2);
}
A simple padding of the values less than 10 could do the trick. So something like the following
function padValue(value) {
if (value < 10) {
return '0' + value;
}
return value;
}
And then for the minutes value, you can write it as follows:
$("#timeSpentSec").html( padValue(parseInt(timeSpentOnSite/1000 % 60)) );
change your function to the following , check for the number of digits in the seconds and mins section by converting them with toString() and callin .length see below
function startCounting() {
timerStart = Date.now();
timer = setInterval(function() {
timeSpentOnSite = getTimeSpentOnSite() + (Date.now() - timerStart);
localStorage.setItem('timeSpentOnSite', timeSpentOnSite);
timerStart = parseInt(Date.now());
// Convert to seconds
let sec = parseInt(timeSpentOnSite / 1000 % 60);
sec = sec.toString().length < 2 ? '0' + sec : sec;
let min = parseInt(timeSpentOnSite / 1000 / 60);
min = min.toString().length < 2 ? '0' + min : min;
$("#timeSpentMin").html(min);
$("#timeSpentSec").html(sec);
}, 1000);
}
To pad a number in JavaScript, you can use the built-in padStart method. You can use the function below to return a formatted string, given integer parameters (if you're passing in strings, you can ignore the toString() call).
function formatTime(hour, minute) {
return `${hour}:${minute.toString().padStart(2, '0')}`;
}
I an a newbie to JS and We created a code for clock that start from end time when reload a same page or moves to next page But this is not working properly. I am showing javascript code of that here . We are adding this to limesurvey js file.
Js code:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(window.location.href) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds ;
if (diff <= 0) {
display.textContent ="Time finished ";
alert("Time is over.Click ok to submit Exam.")
$("#movesubmitbtn").click();
clearInterval(handle);
}
}
// we don't want to wait a full second before the timer starts
timer();
var handle = setInterval(timer, 1000);
}
window.onload = function(){
//set cookie if not exist
if(document.cookie && document.cookie.match('examDuration')){
examTime = document.cookie.match(/(^|;)examDuration=([^;]+)/)[2];
}
else{
timeLimit = getURLParameter('examTime');
document.cookie = 'examDuration='+ 60*timeLimit + '; path=/; ' ;
examTime= 60*timeLimit ;
}
var display = document.querySelector('#time');
startTimer(examTime, display);
$("#movenextbtn").onclick(function(){
remainingTime = (minutes * 60) + seconds ;
document.cookie = 'examDuration='+ remainingTime + '; path=/; ' ;
clearInterval(handle);
});
$("#movesubmitbtn").onclick(function(){
remainingTime = (minutes * 60) + seconds ;
document.cookie = 'examDuration='+ remainingTime + '; path=/; ' ;
clearInterval(handle);
});
};
I don't know why it is not working. I have included JS library link in header of that and have taken all necessary steps were needed. Thanks in advance.
I'm making a stopwatch and out of esthetic reasons I want the output to display: 00:00:00:000. The problem is that when my stopwatch is running I'm having a hard time getting it to except a 0 in front when the value < 10.
window.addEventListener('load', function() {
var display = document.getElementById('display-area');
var toggle = document.getElementById('toggle-button');
var reset = document.getElementById('reset-button');
var ms,
difference,
interval,
hours,
minutes,
seconds,
timer = 0;
function start() {
difference = Date.now();
interval = window.setInterval(update, 10);
timer = 1;
};
function stopp() {
window.clearInterval(interval);
timer = 0;
};
function nullstill() {
ms = 0;
seconds = 0;
minutes = 0;
hours = 0;
display.value = '00:00:00:000';
};
function update() {
ms += elapsedTime();
if (ms >= 1000) {
seconds += 1;
ms = 0;
}
if (seconds >= 60) {
minutes += 1;
seconds = 0;
}
if (minutes >= 60) {
hours += 1;
minutes = 0;
}
display.value = hours + ':' + minutes +':' + seconds +':'+ ms;
};
function elapsedTime() {
var now = Date.now();
elapsed = now - difference;
difference = now;
return elapsed;
};
nullstill();
toggle.addEventListener('click', function() {
console.log(timer);
if (timer != 1) {
start();
} else {
stopp();
}
});
reset.addEventListener('click', function() {
nullstill();
});
});
How do I make it work?
Regards,
An integer will never hold a 0 in front of the number. This is a fairly easy fix. You will just need to use some string concatenation.
display.value = (hours < 10 ? "0"+hours : hours) + ':' + (minutes < 10 ? "0"+minutes : minutes) +':' + (seconds < 10 ? "0"+seconds: seconds) +':'+ ms;
The syntax I have used is called a ternary operator. Here is a little bit about how it works. Basically, it is a simplified if statement which can be used inline.
( condition ? {if true, run this } : {else, run this})
Here's a useful little example that shows you a convenient way to add leading zeros to numbers in Javascript. If you have a number like 53, and want 6 number places (eg 4 leading zeros in the case of 56), you just add (1e6+53+'').slice(-6) and that will give you 000053 because 1e6 means 1 with 6 zeros after it, and slice with a negative number starts from the end and chops out 6 places in this case, so 100000053 becomes 000053
hours=0,minutes=1,seconds=20,ms=7;
document.getElementById('t').innerHTML=
(1e2+hours+'').slice(-2) + ':' +
(1e2+minutes+'').slice(-2) +':' +
(1e2+seconds+'').slice(-2) +':'+
(1e3+ms+'').slice(-3);
<div id='t'></div>
Notice the 1 or 2 leading zeros in the case of ms is handled. And you can adjust the number of leading zeros easily.
This requires string concatenation when the value is less than 10. I would create three separate variables for the hours, minutes and seconds. That way the code is more clean and readable.
var displayHours = (hours >= 10) ? hours : "0" + hours;
var displayMins = (minutes >= 10) ? minutes : "0" + minutes;
var displaySeconds = (seconds >= 10) ? seconds : "0" + seconds;
display.value = displayHours + displayMins + displaySeconds + ":" + ms;
I want to stop this timer when I end the exam, but before it reaches zero. Kindly help me out on scripts please. Thanks.
JavaScript code:
var cnt = 165*60; // 165 minutes (2 hours & 45 minutes) convert to seconds
function countdown() {
if (cnt < 0) {
document.f.c.value = "- : - - : - -" ;
}
else {
hour = Math.floor(cnt / 3600);
totalmin = Math.floor(cnt / 60);
min = totalmin - (hour * 60);
sec = cnt - (totalmin * 60);
if (sec < 10) { sec = "0" + sec;}
if (min < 10) {min = "0" + min;}
if (hour < 10) {hour = "0" + hour;}
document.f.c.value = hour + ":" + min + ":" + sec;
cnt--;
_timer = setTimeout("countdown()", 1000);
}
}
var _timer = setTimeout("countdown()", 1000); // tick
I assume you meant that you want to end the timer before the countdown reaches 0.
First of all, you should use setInterval instead. It should work in all major browsers (including IE). It is just a slightly nicer way to express "I want this to happen every so often." According to the MDN, it:
Calls a function repeatedly, with a fixed time delay between each call to that function.
Here's how you would use it:
var cnt = 165*60; // 165 minutes (2 hours & 45 minutes) convert to seconds
function countdown() {
if (cnt < 0) {
document.f.c.value = "- : - - : - -" ;
}
else {
hour = Math.floor(cnt / 3600);
totalmin = Math.floor(cnt / 60);
min = totalmin - (hour * 60);
sec = cnt - (totalmin * 60);
if (sec < 10) {sec = "0" + sec;}
if (min < 10) {min = "0" + min;}
if (hour < 10) {hour = "0" + hour;}
document.f.c.value = hour + ":" + min + ":" + sec;
cnt--;
if(cnt <= 0) { # Stops the timer when it reaches 0.
clearInterval(_interval);
}
}
}
var _interval = setInterval(countdown, 1000);
And somewhere in your page have a button that will stop the timer.
<input type="button" value="Done" onclick="clearInterval(_interval)">
Although to be honest, having a countdown timer freaks me out. I'd rather have a count-up timer. :-)
In your else part
check
if(current_time < total_time)
{
//Set TimeOut
}
I think your best bet here is to use setInterval rather than setTimeout.
setInterval returns a handle to the interval. clearInterval(handle) will cancel that interval. Here's some pseudo to get you started:
var global_timer;
function countdown(){
// do some countdown stuff
if([we're done]) {
window.clearInterval(global_timer);
}
}
global_timer = window.setInterval("countdown()", 1000);
In the code that you execute when user ends the exam, probably after button click, just add such line:
window.clearTimeout(_timer);
And the timer will stop ticking.