How do I start a timer on a click? - javascript

I'm trying to have a timer start when the user makes the first click on a page. Been doing a lot of research and for the life of me, can't figure it out. I think I should use a document.addEventListener but am not sure where it goes.
let min = 0;
let sec = 0;
function myTimer() {
if (counting) {
timer.innerHTML = min + " minutes " + sec + " seconds";
sec++;
if (sec >= 60) {
sec = 0;
min++;
}
}
}
//Start the timer
let startTimer = setInterval(function() {
myTimer();
}, 1000);

Just add a click listener to document that calls the setInterval:
let min = 0;
let sec = 0;
function myTimer() {
timer.innerHTML = min + " minutes " + sec + " seconds";
sec++;
if (sec >= 60) {
sec = 0;
min++;
}
}
//Start the timer
document.addEventListener('click', () => {
setInterval(myTimer, 1000);
}, { once: true });
<div id="timer">click somewhere</div>

Given a button with id button as so:
<button id="button">Click me</button>
the most basic way to add an event listener for that button to start the timer is by retrieving the element from dom (using querySelector or getElementById), then add a named event listener function to the element in the dom, such as onclick:
document.querySelector('#button').onclick = function(){
//your code to start timeer here
};
but you can also do it using addEventListener:
document.querySelector('#button').addEventListener('click',function(){
//your code to start timeer here
});
or with event delegation, you can add a global click handler to the document, check if the target element was the button, and if so you can then start the timer:
document.addEventListener('click',function(event){
if(event.target.id==='button'){
//your code to start timer here
}
});
there are 900 ways to skin a cat in modern javascript, its up to you to decide which one is most appropriate, and sometimes its a matter of personal preference.

Related

timer starts automatically instead of on a button press in javascript

I'm quite new to javascript so the answer is probably quite easy but anyways
I'm trying to make a simple click speed test but i cant get the timer to start when the user presses the click me button, so i resorted to just starting it automatically. if anyone can help me to start it on the button press it will be much appreciated
HTML code:
<button id="click2" onclick="click2()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="10stimer">10s</span>
JS code:
var click = document.getElementById("click2");
var amount = 0;
var seconds = 10;
var endOfTimer = setInterval(click2, 1000);
function click2() {
seconds--;
document.getElementById("10stimer").innerHTML = seconds + "s";
if (seconds <= 0) {
var cps = Number(amount) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("click2").disabled = true;
document.getElementById("10stimer").innerHTML = "Ended";
clearInterval(seconds);
}
}
document.getElementById("click2").onclick = function() {
amount++;
document.getElementById("clicksamount").innerHTML = amount + " Clicks";
}
It looks like you're overwriting your onclick function on the button with id click2 with the lowest 4 lines.
Also, you call clearInterval() with the seconds variable instead of the actual interval, which is referenced by endOfTimer.
I'd suggest to have a separated timer management in a function which you call only on the first click of your button.
See JSFiddle
<button id="clickbutton" onclick="buttonClick()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="secondcount">10s</span>
// We will have timerStarted to see if the timer was started once,
// regardless if it's still running or has already ended. Otherwise
// we would directly restart the timer with another click after the
// previous timer has ended.
// timerRunning only indicates wether the timer is currently running or not.
var timerStarted = false;
var timerRunning = false;
var seconds = 10;
var clickAmount = 0;
var timer;
function buttonClick() {
if (!timerStarted) {
startTimer();
}
// Only count up while the timer is running.
// The button is being disabled at the end, therefore this logic is only nice-to-have.
if (timerRunning) {
clickAmount++;
document.getElementById("clicksamount").innerHTML = clickAmount + " Clicks";
}
}
function startTimer() {
timerStarted = true;
timerRunning = true;
timer = setInterval(timerTick,1000);
}
function timerTick() {
seconds--;
document.getElementById("secondcount").innerHTML = seconds + "s";
if (seconds <= 0) {
timerRunning = false;
clearInterval(timer);
var cps = Number(clickAmount) / 10;
document.getElementById("clickbutton").disabled = true;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS (" + clickAmount + "clicks in total)!";
}
}
I made some changes to your code. Effectively, when the user clicks the first time, you start the timer then. The timer variables is null until the first the user clicks.
var click = document.getElementById("click2");
var noOfClicks = 0;
var seconds = 10;
var timer = null;
function doTick(){
seconds--;
if(seconds<=0){
seconds = 10;
clearInterval(timer);
document.getElementById("10stimer").innerHTML= "Ended"
timer=null;
document.getElementById("click2").disabled = true;
}
updateDisplay()
}
function updateClicks(){
if(!timer){
timer=setInterval(doTick, 1000);
clicks= 0;
seconds = 10;
}
noOfClicks++;
updateDisplay();
}
function updateDisplay(){
var cps = Number(noOfClicks) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("10stimer").innerHTML =seconds;
}
click.addEventListener('click', updateClicks)
https://jsbin.com/bibuzadasu/1/edit?html,js,console,output
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
Use event listeners rather than onclicks
usage example:
HTML
<button id="mybutton">Click me!</button>
JS
/* ABOVE CODE ... */
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
<button id="mybutton">Click me!</button>
//state initialization
var amount = 0;
var seconds = 10;
var timedOut=false;
var timerId=-1;
//counters display
var clicksDisplay= document.getElementById("clicksamount");
var timerDisplay= document.getElementById("10stimer");
function click2(e){
//first click
if(timerId===-1){
//start timer
timed();
}
//still in time to count clicks
if(!timedOut){
amount++;
clicksDisplay.innerText=amount +" Clicks";
}
}
function timed(){
//refresh timer dispaly
timerDisplay.innerText=seconds+"s";
seconds--;
if(seconds<0){
//stop click count
timedOut=true;
}else{
//new timerId
timerId=setTimeout(timed,1000);
}
}

How to stop the time from running after pressing "stop" on stopwatch

I have created this stopwatch and it runs pretty well. The only problem that I am having is that whenever I click my "stop" button, the time stops on the screen but it is still running in the background.
Is there any way to stop this from happening? I want the timer to stop on its current time, then when I click "start", it resumes from the time it was stopped on.
Im thinking maybe create a "new Date()" variable before the update function and another "new Date()" variable inside of the update function and somehow subtract those to get the current date. But I cannot figure that out either.
start = document.getElementById('Start');
stop = document.getElementById('Stop');
let watchRunning = false;
Start.addEventListener('click', startHandler);
Stop.addEventListener('click', stopHandler);
function startHandler() {
if (!watchRunning) {
watchRunning = setInterval(update, 70);
}
}
function stopHandler() {
clearInterval(watchRunning);
watchRunning = null;
}
update();
var seconds;
var milliseconds;
var d;
function update() {
d = new Date();
seconds = d.getSeconds();
milliseconds = Math.floor((d.getMilliseconds() / 10));
if (milliseconds < 10 && seconds < 10) {
document.getElementById("Time").innerHTML =
"0" + seconds + ".0" + milliseconds;
} else if (milliseconds < 10 && seconds >= 10) {
document.getElementById("Time").innerHTML =
seconds + ".0" + milliseconds;
} else if (milliseconds >= 0 && seconds < 10) {
document.getElementById("Time").innerHTML =
"0" + seconds + "." + milliseconds;
} else if (milliseconds >= 0 && seconds >= 10) {
document.getElementById("Time").innerHTML =
seconds + "." + milliseconds;
}
}
#Time {
background-color: yellow;
max-width: 2.3%;
}
<h1>Stop Watch</h1>
<button id="Start">Start</button>
<button id="Stop">Stop</button>
<h3>Elapsed Time:</h3>
<p id="Time"></p>
Try running the snippet and you will see what I mean. The time doesn't stop "running" after I click stop, and when I click start it resumes as if it was never stopped.
clearTimeout( return ID of setTimeout() );
clearTime variable is returned as a value by the setTimeout( ) timing method, which can be pass to the clearTimeout( ID ) as an ID to reference it - clearTimeout( clearTime );
How It Works
Whenever the clearTimeout( ) timing method is called on a setTimeout( ) timing method that is active, the clearTimeout( ) timing method will stop the execution of the setTimeout( ) timing method but without destroying its execution entirely.
The setTimeout( ) timing method is left idle during the period that the clearTimeout( ) timing method is called, and when you re-execute the setTimeout( ) timing method, it will start from the point its execution was stopped, not starting all over from the beginning.
You're good to go!
You should use a setInterval to run your code to update the stopwatch instead of relying on a Date; you can not stop the Date from changing, so even though you stopped updating your stopwatch, the seconds are still ticking by which makes it seem like your stopwatch never stopped.
#Time {
background-color: yellow;
max-width: 2.3%;
}
<h1>Stop Watch</h1>
<button id="Start">Start</button>
<button id="Stop">Stop</button>
<h3>Elapsed Time:</h3>
<p id="Time">00:00</p>
<script>
var start = document.getElementById('Start'), stop = document.getElementById('Stop'), time = document.getElementById('Time');
function StopWatch(props){
this.seconds = props.seconds||0;
this.milliseconds = props.milliseconds||0;
this.updateCallback = props.updateCallback;
this._running = false;
}
StopWatch.prototype = {
start: function(){
var _this = this;
if(!_this._running){
_this._running = true;
_this._intervalID = window.setInterval(function(){
if(++_this.milliseconds==100){
_this.seconds++;
_this.milliseconds = 0;
}
if(_this.updateCallback){
_this.updateCallback(_this.milliseconds, _this.seconds);
}
}, 10);
}
},
stop: function(){
window.clearInterval(this._intervalID);
this._running = false;
},
getTimeString: function(){
var ms = this.milliseconds, s = this.seconds;
if(ms<10){
ms = "0"+ms;
}
if(s<10){
s = "0"+s;
}
return s + ":" + ms;
}
}
var sw = new StopWatch({updateCallback: function(){
time.textContent = sw.getTimeString();
}});
start.addEventListener('click', function(){
sw.start();
});
stop.addEventListener('click', function(){
sw.stop();
});
</script>

Pause / Resume jQuery Countdown Timer

I'm trying to make a countdown timer that can be paused with a single HTML5 button tag using a JS onClick() event, or more preferably, using jQuery with something like $("#pause_resume").off('click').on('click', firstClick)in conjunction with another function. Logically, I would assume the task would require getting the current values of both $.min and $.sec and then setting these values, while switching functions, until the "resume" button is pressed again. But I honestly have no idea how to go about doing this. I've looked at other code on this site and others, but what I saw was heavily deprecated and not in line with my project plan. Any insight is appreciated.
HTML:
<p class="timer">
<span class="min"></span>:<span class="sec"></span>/
<span class="fullTime">1:30</span>
</p>
JavaScript:
<script type="text/javascript">
var timer = $('.timer');
var leadingZero = function(n) {
if (n < 10 && n >= 0)
return '0' + n;
else
return n;
};
var minutes = 1;
var seconds = 30;
setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds == 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
</script>
Well, I think this is what you want. http://jsfiddle.net/joey6978/67sR2/3/
I added a button that toggles a boolean on click to determine whether to set your function in the interval or to clear the interval.
var clicked=true;
var counter;
$('button').click(function(){
if(clicked){
counter=setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds === 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
}
else{
clearInterval(counter);
}
clicked=!clicked;
});

Reset javascript function

I am having trouble getting a javascript function to reset itself after an onclick event. When I click the "Start" button the counter begins to count up. But when I click the "Reset" button nothing happens. I need the timer to reset to "0:00" and wait for me to click "Start" again. Here is my code:
<script type="text/javascript">
var seconds = 0;
var minutes = 0;
function zeroPad(time) {
var numZeropad = time + '';
while(numZeropad.length < 2) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}
function countSecs() {
seconds++;
if (seconds > 59) {
minutes++;
seconds = 0;
}
document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
}
function startTimer() {
action = window.setInterval(countSecs,1000);
}
function resetTimer() {
var seconds = 0;
var minutes = 0;
}
</script>
<body>
<button onclick = "startTimer()">Start</button>
<div id="timeBox">Time 00:00</div>
<button onclick = "resetTimer">Reset</button>
</body>
Call the clearInterval() method.
function resetTimer() {
window.clearInterval(action);
}
This is a scoping issue, using var inside a function, makes seconds and minutes local to that function. Removing the leading var will start you off in the right direction.
function resetTimer() {
seconds = 0;
minutes = 0;
}
Onclick events must call functions like: onclick="resetTimer();" with the parenthesis at the end. Some browsers may try to submit on button clicks if you don't define type="button". I didn't assume you wanted reset timer to stop the timer so I added a stop button.
http://jsfiddle.net/iambriansreed/WRdSK/
<button type="button" onclick="startTimer();">Start</button>
<div id="timeBox">Time 00:00</div>
<button type="button" onclick="resetTimer();">Reset</button>
<button type="button" onclick="stopTimer();">Stop</button>
<script>
window.seconds = 0;
window.minutes = 0;
function startTimer() {
window.action = setInterval(countSecs,1000);
}
function resetTimer() {
seconds = 0;
minutes = 0;
}
function stopTimer() {
clearInterval(action);
seconds = -1;
minutes = 0;
countSecs();
}
function zeroPad(time) {
var numZeropad = time + '';
while(numZeropad.length < 2) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}
function countSecs() {
seconds++;
if (seconds > 59) {
minutes++;
seconds = 0;
}
document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
}
</script>
​
You have two errors in your code:
First, in the button you missed the () after the function's name in order to make an actual call:
<button onclick = "resetTimer()">Reset</button>
Second, you did not stop the interval using window.clearInterval() (MDN docu), so the timer went on and on.
// just to make it an explicit global variable. already was an implicit one.
var action;
// rest of your code
function resetTimer() {
// clear the timer
window.clearInterval( action );
// reset variables
var seconds = 0;
var minutes = 0;
// update output
document.getElementById("timeBox").innerHTML = "Time " + zeroPad(minutes) + ":" + zeroPad(seconds);
}
I set up a working fiddle here.

How to set one minute counter in javascript?

In my project ,I have list of questions, for every question have three option answers.
After see the question if i want answer that question means click "show answer" button .
when I click button ,counter starts for one minute after one minute error will show .
can any one help ?
You could use something like this:
function gameLost() {
alert("You lose!");
}
setTimeout(gameLost, 60000);
UPDATE: pass function reference to setTimeout() instead of code string (did I really write it that way? O_o)
EDIT
To display the timer too (improved version, thanks to davin too):
<button onclick="onTimer()">Clickme</button>
<div id="mycounter"></div>
<script>
i = 60;
function onTimer() {
document.getElementById('mycounter').innerHTML = i;
i--;
if (i < 0) {
alert('You lose!');
}
else {
setTimeout(onTimer, 1000);
}
}
</script>
......
function timedOut() {
alert("Some error message");
}
// set a timer
setTimeout( timedOut , 60000 );
That basically sets a timer that will execute the given function after 60.000 miliseconds = 60 seconds = 1 minute
Edit: here's a quick, imperfect fiddle that also shows the countdown http://jsfiddle.net/HRrYG
function countdown() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "0:" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
}
// start the countdown
countdown();
You will want to use the setTimout function check out this article. https://developer.mozilla.org/En/Window.setTimeout Remember the timer is in milliseconds so for one minute is 60,000.
// this is the simplest way to one mint counter .this is also use in angular and oops
var i=60;
function coundown(){
setInterval(() => {
if (this.i == 0) {
return;
}
console.log(this.i--);
}, 1000);
}
// this function you can call when otp is comming or form submit and waiting for otp countdown
angular #javascript #typescript
you can try to use this
or visit for more details Demo
Demo2
function countdown() {
var seconds = 59;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML =
"0:" + (seconds < 10 ? "0" : "") + String(seconds);
if (seconds > 0) {
setTimeout(tick, 1000);
} else {
document.getElementById("verifiBtn").innerHTML = `
<div class="Btn" id="ResendBtn">
<button type="submit">Resend</button>
</div>
`;
document.getElementById("counter").innerHTML = "";
}
}
tick();
}
countdown();
<div class="btnGroup">
<span class="Btn" id="verifiBtn">
<button type="submit">Verify</button>
</span>
<span class="timer">
<span id="counter"></span>
</span>
</div>

Categories