I wrote this easy JS timer and i have problem with if for minutes, it still writing in first sec 00:01, second sec 000:02...... If you understand me. Please can you help me? Thank you
var sec = 0;
var min = 0;
var time;
function timer() {
sec++;
if (sec < 10) {
sec = "0" + sec;
}
if (min < 10) { //here is problem I think
min = "0" + min;
}
if (sec == 60) {
sec = 0;
min++;
}
if (sec == 5) { //this is just a function test
document.getElementById("myForm").submit();
}
document.getElementById("myTimer").innerHTML = min + ":" + sec;
}
function start() {
time = setInterval("timer()", 1000);
}
Each time your function runs, it adds a zero to the beginning of min, which is a global variable. That's why it works the way it does.
You could use a temporary variable for holding the time as string.
var sec = 0;
var min = 0;
var time;
function timer() {
sec++;
var minStr = (min < 10) ? '0' + min : '' + min;
var secStr = (sec < 10) ? '0' + sec : '' + sec;
document.getElementById("myTimer").innerHTML = minStr + ":" + secStr;
}
function start() {
time = setInterval("timer()", 1000);
}
start();
<div id="myTimer"></div>
Related
I would like to make the time display that time 01: 02: 03:43, but I get 0:0:00000000000000001:15 I tired add 0 in dev **0:0:0:0, but it doesn't work. Is it good code for timer?
var hour = 0;
var min = 0;
var sec = 0;
var miliSec = 0;
var timer;
function callTimer() {
miliSec++;
if (miliSec < 100) {
if (miliSec === 99) {
miliSec = 0;
sec++;
if (sec === 60) {
sec = 0;
min++;
if (min === 60) {
min = 0;
hour++
}
}
}
} else {
miliSec = 0;
}
document.getElementById("#timer").innerHTML = hour + ":" + min + ":" + sec + ":" + miliSec;
}
function start() {
document.getElementById("#start").disabled = true;
timer = setInterval(callTimer, 10);
}
function stop() {
document.getElementById("#start").disabled = false;
clearInterval(timer);
}
function reset() {
stop();
hour = 0;
min = 0;
sec = 0;
miliSec = 0;
document.getElementById("#timer").innerHTML = hour + ":" + min + ":" + sec + ":" + miliSec;
}
I have to give more details about this problem, because validation don't allow post me that problem. Well I wrote this ;)
I added toString().padStart(2, "0") to each element.
You can read more about padStart() here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
var hour = 0;
var min = 0;
var sec = 0;
var miliSec = 0;
var timer;
function callTimer() {
miliSec++;
if (miliSec < 100) {
if (miliSec === 99) {
miliSec = 0;
sec++;
if (sec === 60) {
sec = 0;
min++;
if (min === 60) {
min = 0;
hour++
}
}
}
} else {
miliSec = 0;
}
/* Add 0 every time -- This does not work because it changes the type from a number to string, causing the unexpected behavior
if (sec < 10) {
sec = "0" + sec;
}else{
sec;
}
*/
document.getElementById("#timer").innerHTML = hour.toString().padStart(2, "0") + ":" + min.toString().padStart(2, "0") + ":" + sec.toString().padStart(2, "0") + ":" + miliSec;
}
function start() {
document.getElementById("#start").disabled = true;
clearInterval(timer);//stop any previous interval before starting another
timer = setInterval(callTimer, 10);
}
function stop() {
document.getElementById("#start").disabled = false;
clearInterval(timer);
}
function reset() {
stop();
hour = 0;
min = 0;
sec = 0;
miliSec = 0;
document.getElementById("#timer").innerHTML = hour.toString().padStart(2, "0") + ":" + min.toString().padStart(2, "0") + ":" + sec.toString().padStart(2, "0") + ":" + miliSec;
}
<nav class="controls">
START
STOP
CLEAR
</nav>
<div id="#timer">00:00:00:0</div>
Instead of keeping four counters, you could very easily get the delta in milliseconds on every run of the callTimer callback and then do a few simple calculations to get seconds, hours, weeks... whatever the time units you may need. Something along these lines should do the trick:
var startTS
function formatNumber(num, digits) {
return `000${num}`.slice(-digits) // Get last X digits (in our case will be either 2 or 3)
}
function callTimer() {
const currentTS = Date.now()
const elapsed = currentTS - startTS // Elapsed time in milliseconds
const elapsedSec = Math.floor(elapsed/1000) // Whole seconds
const elapsedMin = Math.floor(elapsedSec/60) // Whole minutes
const elapsedHr = Math.floor(elapsedMin/60) // Whole hours
...
const msec = elapsed % 1000 // Get the "milliseconds" part
const sec = elapsedSec % 60 // Seconds part
const min = elapsedMin % 60 // Minutes
const hr = elapsedHr % 60 // Hours
const fmtStr = `${formatHumber(hr,2)}:${formatNumber(min,2)}:${formatNumber(sec,2)}.${formatNumber(msec,3)}`
document.getElementById("#timer").innerHTML = fmtStr
}
...
function start() {
document.getElementById("#start").disabled = true;
startTS = Date.now()
timer = setInterval(callTimer, 10);
}
...
Hope that helps!
I'm trying to make a count down timer. Here's my code:
var t = setInterval(countDown, 1000);
var startTime = new Date().getTime() + (5 * 1000);
function countDown() {
var now = new Date().getTime();
var milisecDistance = startTime - now;
var min = Math.floor(milisecDistance / (1000 * 60));
var sec = Math.floor(milisecDistance % (1000 * 60) / 1000);
//if(milisecDistance<0){
// document.getElementById("time").innerHTML = "Time over!";
// clearInterval(t);
//}
document.getElementById("time").innerHTML = min + " : " + sec;
if (milisecDistance < 0) {
document.getElementById("time").innerHTML = "Time over!";
clearInterval(t);
}
}
<span id="time">00 : 5</span>
It work fine when I put the if statement in the end of the function. But I think it is more reasonable to put the if statement before
document.getElementById("time").innerHTML = min + " : " + sec;
Otherwise, when milisecDistance become negative, it may replace the text with "-1 : -1" before it stop "setInterval".
However, when I do this, it stop at "-1 : -1" and didn't print "Time over!".
I was confused, can anyone explain this?
edit:
Sorry that my question is not clear. I'm asking when I put the if statement after document.getElementById("time").innerHTML = min + " : " + sec; it just print "Time over!" after "0 : 0". However, I don't understand why. I think the code should print "-1 : -1" first, then print "Time over!".
If atomic accucary isn't required:
var div = document.getElementById("time");
var leadOneZero = n=>(n < 10 ? "0" : "") + n;
var writeTime = (min,sec)=>div.innerHTML = leadOneZero(min) + ":" + leadOneZero(sec);
var sec = 5;
var t = setInterval(countDown, 1000);
countDown();
function countDown() {
var min = Math.floor(sec / 60);
writeTime(min, sec % 60);
sec--;
if (sec < 0) {
div.innerHTML = "Time over!";
clearInterval(t);
}
}
<span id="time"></span>
Pseudocode for the simplest solution with minimal changes
If (millisecDistance < 0){
print("Time over")
clearInterval()
Else
print(sec)
I found a sample JavaScript count up timer that meets my needs, including a start/pause and reset function. However it's missing one thing that I need it to do; have the script add 2 seconds to the display timer when a button is selected.
Here is my HTML:
<!doctype html>
<html>
<head>
<title></title>
</head>
<p><span id="my_timer" style="color: #f00; font-size: 2000%; font-weight: bold;">00:00:00</span></p>
<button id="control" onclick="changeState();">START</button>
<button id="reset" onClick="reset();">RESET</button>
<button id="updateClock" onClick="updateClock();">2 SECONDS</button>
<script type="text/javascript" src="timer.js"></script>
<body>
</body>
</html>
And here is my JavaScript:
// boolean keeps track of timer state
var active = false;
//main function
function start_timer() {
//function active if true
if (active) {
var timer = document.getElementById("my_timer").innerHTML;
var arr = timer.split(":"); //spliting timer into array by ':', so hour goes to arr[0], minutes go to arr[1], etc.
var hour = arr[0]; //getting hour
var min = arr[1]; //minutes
var sec = arr[2]; //seconds
if (sec == 59) {
if (min == 59) {
hour++;
min = 0;
if (hour < 10) hour ="0" + hour;
} else {
min++;
}
if (min < 10) min = "0" + min;
sec = 0;
} else {
sec ++;
if (sec < 10) sec = "0" + sec;
}
//update our html
document.getElementById("my_timer").innerHTML = hour + ":" + min + ":" + sec;
setTimeout(start_timer, 1000); //repeat with speed of 1 second
}
}
//functions to change states - start or pause timer by clicking
function changeState () {
if (active == false) {
active = true;
start_timer();
console.log("Timer has been started");
document.getElementById("control").innerHTML = "PAUSE";
} else {
active = false;
console.log("Timer is on pause");
document.getElementById("control").innerHTML = "START";
}
}
//reset function
function reset() {
document.getElementById("my_timer").innerHTML = "00" + ":" + "00" + ":" + "00";
console.log("Timer has been reset");
}
How would I script a function that would add 2 seconds to the display timer?
Below only works while the timer is running. To get the button to add two seconds whether the timer is running or not, remove the 'if (active){'.
// add two seconds to displayed time
function start_timer(){
if (active) {
var timer = document.getElementById("my_timer").innerHTML;
var arr = timer.split(":"); //spliting timer into array by ':', so hour goes to arr[0], minutes go to arr[1], etc.
var hour = arr[0]; //getting hour
var min = arr[1]; //minutes
var sec = arr[2]; //seconds
if ((sec == 58) || (sec == 59)) {
if (min == 59) {
hour++;
min = 0;
if (hour < 10) hour ="0" + hour;
} else {
min++;
}
if (min < 10) min = "0" + min;
if (sec == 58){
sec = 0;
}
if (sec == 59){
sec = 1;
}
} else {
sec = parseInt(sec) + 2;
if (sec < 10) sec = "0" + sec;
}
//update our html
document.getElementById("my_timer").innerHTML = hour + ":" + min + ":" + sec;
}
}
Suppose you wanted to set a timer to whatever time you want will be displayed in the form 00:00:00 minutes, seconds, and hundredths. How would you go about doing so? Please any help is greatly appreciated.
Here is the link in JSFiddle:
https://jsfiddle.net/mxpuejvz/2/
function decrement(){
var time = 600;
var mins = parseInt((time / 100) / 60);
var secs = parseInt((time / 100) % 60);
var hundredths = parseInt(time % 100);
if(mins < 10) {
mins = "0" + mins;
}
if(secs < 10) {
secs = "0" + secs;
}
if(hundredths < 10) {
hundredths = "0" + hundredths;
}
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + hundredths;
if (hundredths === 0){
if(time ===0){
clearInterval(countdownTimer);
document.getElementById("output").innerHTML = "Time's Up.";
}else{
time--;
}
var countdownTimer = setInterval('decrement()', 10)
}
}
}
Three issues appear to need attention.
"time to go" needs to be stored outside the screen update function and decremented or calculated each time the screen is updated.
using parseInt to convert numbers to integer numbers is regarded as a hack by some. Math.floor() or integer calculation can be alternatives.
Timer call backs are not guaranteed to made exactly on time: counting the number of call backs for a 10msec time does not give the number of 1/100ths of elapsed time.
The following code is an example of how it could work, minus any pause button action.
var countdownTimer;
var endTime;
var counter = 0; // ** see reply item 3. **
function startCountDown( csecs) // hundredths of a second
{ endTime = Date.now() + 10*csecs; // endTime in millisecs
decrement();
countdownTimer = setInterval(decrement, 10);
counter = 0; // testing
}
function decrement()
{ var now, time, mins, secs, csecs, timeStr;
++ counter; // testing
now = Date.now();
if( now >= endTime)
{ time = 0;
timeStr = "Times up! counter = " + counter;
clearInterval( countdownTimer);
}
else
{ time = Math.floor( (endTime - now)/10); // unit = 1/100 sec
csecs = time%100;
time = (time-csecs)/100; // unit = 1 sec
secs = time % 60;
mins = (time-secs)/60; // unit = 60 secs
timeStr =
( (mins < 10) ? "0" + mins : mins) + ":" +
( (secs < 10) ? "0" + secs : secs) + ":" +
( (csecs < 10) ? "0" + csecs : csecs);
}
document.getElementById("output").innerHTML=timeStr;
}
The argument to startCountDown gives the number of 1/100ths of second for the count down. If the counter result is the same as the argument,try swapping browser tabs and back again during the countdown.
HTML to test:
<button type="button" onclick="startCountDown(600)">start</button>
<div id="output">
</div>
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);
}