This timer works successfully, but I’d like to add a 1 second delay before it starts, here’s the code:
var Clock = {
totalSeconds: 0,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));
}, 1000);
}
},
reset: function () {
Clock.totalSeconds = null;
clearInterval(this.interval);
document.getElementById("min").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
delete this.interval;
},
stop: function () {
clearInterval(this.interval);
delete this.interval;
}
};
document.getElementById("start").addEventListener("click", function () { Clock.start(); });
document.getElementById("stop").addEventListener("click", function () { Clock.stop(); });
any help is appreciated
also, how can I modify it so that it displays this: 0:00 instead of 00:00 ?
thanks
The start is a good place to add a 1 second delay:
document.getElementById("start").addEventListener("click", function () {
setTimeout(function () {
Clock.start();
}, 1000)
});
[Edit: added missing parenthesis]
To display 0 for the minutes, you would remove 00 from the minutes section.
// document.getElementById("min").innerHTML = "00";
document.getElementById("min").innerHTML = "0";
I presume you also want the updated minutes to not be double digits either. That’s when you remove the padding from them.
// document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
document.getElementById("min").innerHTML = Math.floor(self.totalSeconds / 60 % 60);
Thanks again for your kind assistance.
However, I’m doing something wrong I’m sure because the time is no longer displayed with this:
var Clock = {
totalSeconds: 0,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
// document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
document.getElementById("min").innerHTML = Math.floor(self.totalSeconds / 60 % 60);
document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));
}, 1000);
}
},
document.getElementById("start").addEventListener("click", function () {
setTimeout(function () {
Clock.start();
}, 1000
});
etc...
any additional guidance is welcomed.
Is there a test page that I can experience this on?
Got it. Thanks again
document.getElementById("start").addEventListener("click", function () {
setTimeout(function () {
Clock.start();
}, 1000); //missing bracket
});
1 Like
system
Closed
6
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.