The stop button for my pomdoro clock does not function - javascript

I am building a pomodoro clock with start and stop button. I have the start button functioning, but not the stop button. Here is my code:
HTML:
<h1> Pomodoro Clock</h1>
<!--Place holder for timer-->
<div id="timer" class="circle">Timer</div>
<!--//Start Button-->
<button onclick="setTimeout(timer, 1000);">Start</button>
<!--Stop Button-->
<button onclick="timer.stopTimer()">Stop</button>
JS:
var i = 1500;
var timeHandler;
document.getElementById("timer").innerHTML = i;
function timer() {
timeHandler = setInterval(function() {
if (i > 0) {
i--;
document.getElementById("timer").innerHTML = i;
}
}, 1000);
function stopTimer() {
clearTimeout(timeHandler);
}
}
I would prefer a vanilla JS solution.

Try this:
HTML
<!--Stop Button-->
<button onclick="stopTimer()">Stop</button>
JS
var i = 1500;
var timeHandler;
document.getElementById("timer").innerHTML = i;
function timer() {
timeHandler = setInterval(function() {
if (i > 0) {
i--;
document.getElementById("timer").innerHTML = i;
}
}, 1000);
}
function stopTimer() {
clearTimeout(timeHandler);
}

Related

stop interval inside a function

I have this script that runs a soccer game clock,
when I click the start button everything is working properly
but I can't stop the clock.
var count;
function gameClock() {
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
var count = setInterval(function() {
setTime()
}, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
}
//Start Stop Game Clock
$(document).on('click', '#f_start', function() {
$("#half_name").text('FIRST HALF');
gameClock();
// localStorage.setItem('first_half_click', getTime());
// localStorage.setItem('half', 1);
})
$(document).on('click', '#f_stop', function() {
clearInterval(count);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-2">
<button class="btn btn-success" id="f_start"> START</button>
</div>
<div class="col-2">
<button class="btn btn-danger" id="f_stop"> STOP</button>
</div>
You are redeclaring the count global variable inside the gameClock method which means it's scope is only in that function. change the assignment to use the global count variable instead of the useless local variable.
var count = setInterval(function() {
setTime()
}, 1000);
//to
count = setInterval(function() {
setTime()
}, 1000);

Pause and start JS countdown timer

I am trying to develop a centurion countdown timer for my website. It is a drinking game.
The way the timer works is: It is a 60 second countdown timer. Everytime the timer hits 0 it will +1 a shot counter and restart. It will do this 100 times.
The game is you must do 1 shot, every minute for 100 minutes. I am a beginner at JS and I am learning a lot, but I am seriously struggling to get this to work the way I want it to.
All I need is a "Start" Button, a "Pause" button and a "Reset" button but I can't seem to find a way to make these buttons work without messing the timer up.
Here is the HTML code:
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="timer()">
<input type="button" value="Pause" onclick="clearInterval(myTimer)">
</div>
and here is the JS code:
var seconds = 60;
var shots = 0;
var timer;
var c = 60;
function timer() {
timer = setInterval(myTimer, 1000)
}
function myTimer() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
If anyone could help me and show me what I am doing wrong and how I can make the code better, please do!
First, consider renaming either your method timer() or variable timer to disambiguate between the two.
Next, setInterval() returns an interval ID, which you store in timer.
clearInterval() takes the interval ID as the parameter, so try passing it the timer variable instead of myTimer (a function)
Little bit clean up needed. For clearInterval, u have to id of timer to clear
var seconds = 60;
var shots = 0;
var timer;
var c = 60;
function start() {
clearInterval(timer)
timer = setInterval(( ) =>{
updateUi()
}, 1000);
}
function pause() {
clearInterval(timer)
}
function updateUi() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="start()">
<input type="button" value="Pause" onclick="pause()">
</div>
You can also use Pub Sub model, to make code looks clean.
var seconds = 60;
var shots = 0;
var c = 60;
function Emitter() {
this.cb;
this.on = cb => {
this.cb = cb;
};
this.emit = () => {
this.cb && this.cb();
};
this.cancel = () => {
this.cb = null;
};
}
const emitter = new Emitter();
const tick = () => {
setInterval(() => {
emitter.emit();
}, 1000);
};
tick()
function start() {
emitter.on(updateUi);
}
function pause() {
emitter.cancel();
}
function updateUi() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="start()">
<input type="button" value="Pause" onclick="pause()">
</div>
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="minutes">100</p>
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="START" onclick="start()">
<input type="button" value="PAUSE" onclick="pause()">
<input type="button" value="RESET" onclick="reset()">
</div>
Changed the onclick functions to something more meaningful. Added an extra button and some more logic to auto-stop when hitting the 100 minutes.
var seconds = 60,
minutes = 100,
shots = 0;
timer = "";
// this will just stop the timer, if you click start it will resume from where it left off
function pause() {
clearInterval(timer);
}
// resets seconds/minutes/shots, stops game
function reset() {
clearInterval(timer);
seconds = 60;
minutes = 100;
shots = 0;
timer = "";
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML = c;
document.getElementById("shots").innerHTML = shots;
}
// starts game from wherever it was left
function start() {
timer = setInterval(function() {
document.getElementById("seconds").innerHTML = c--;
if (c === 0) {
document.getElementById("minutes").innerHTML = --minutes;
// when 100 minutes are up, game will stop and reset
if (minutes === 0) {
reset();
}
shots++;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}, 1000)
}

How to get a working countdown timer with a button that adds +1 to a counter after every click

I am setting up a project for class which I need to use jquery. I have settled on a project whereby you would click the button, the counter would increase by one and a timer would start. This would act like a game to see how fast you can click in 10 seconds.
$("#button").mousedown(function () {
score = score + 1;
startTimer();
});
function startTimer() {
if (stop === 0) {
stop = stop + 1;
var counter = 0;
var interval = setInterval(function () {
counter++;
display = 60 - counter;
$("#button").html("Click! (" + display + " secs)");
if (counter == 60) {
alert("Times up!");
clearInterval(interval);
stop = 0;
endscore = score;
score = 0;
}
}, 1000);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clicks">
<p><span>0</span></p>
</div>
<div class="boxtext">
<p>Time Remaining: <span>10</span> Seconds </p>
</div>
<div class="but">
<button type="button" name="button">Click</button>
</div>
I expected the timer to start and the counter to increase by one but nothing happens at all.
You need to:
Add an id to your button:
<button id="button" type="button" name="button">Click</button>
Also you need to define the score & stop variables globally outside the function:
var score = 0;
var stop = 0;
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var score=0;
var stop=0;
var counter = 0;
var endscore=0;
$("button").mousedown(function () {
score = score + 1;
$("#score").text(score);
startTimer();
});
function startTimer() {
if (stop === 0) {
stop = stop + 1;
var interval = setInterval(function () {
counter++;
display = 60 - counter;
// $("button").html("Click! (" + display + " secs)");
if (counter == 60) {
alert("Times up!");
clearInterval(interval);
stop = 0;
endscore = score;
score = 0;
}
$('#timeRemaining').text(display);
}, 1000);
}
};
});
</script>
</head>
<body>
<div class="clicks">
<p><span id="score">0</span></p>
</div>
<div class="boxtext">
<p>Time Remaining: <span id="timeRemaining">60</span> Seconds </p>
</div>
<div class="but">
<button type="button" name="button">Click</button>
</div>
</body>
</html>
You're using as selector an ID, however your button element doesn't have that ID. You can do the following:
Add the id to that button.
Or, you can change the selector as:
$(".but").mousedown(function() { // or $('button[name="button"]').mousedown(function() {...});
score = score + 1;
startTimer();
});
From your html you didn't have id="button" so use name selector or assign id to the button.
Like below.
$("input[name='button']").mousedown(function() {
score = score + 1;
startTimer();
});
You forgot to initialize some variables and give some ids.
var score = 0
var stop = 0
$("#button").click(function () {
score = score + 1;
startTimer();
});
function startTimer() {
console.log('start timer')
if (stop === 0) {
stop = stop + 1;
var counter = 0;
var interval = setInterval(function () {
console.log('#interval')
counter++;
display = 60 - counter;
$("#button").html("Click! (" + display + " secs)");
if (counter == 60) {
alert("Times up!");
clearInterval(interval);
stop = 0;
endscore = score;
score = 0;
}
$('#counter').html(counter)
}, 1000);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clicks">
<p><span id="counter">0</span></p>
</div>
<div class="boxtext">
<p>Time Remaining: <span>10</span> Seconds </p>
</div>
</div>
<div class="but">
<button type="button" id="button">Click</button>
</div>

javascript bug using setTimeout()

I have this program which tells you your reaction time, and it works fine, but if you run the program and click the start button twice, instead of once, the background turns red right away, instead of waiting for the set interval. Thanks in advance to anyone that can help.
<!DOCTYPE html>
<html>
<head>
<script>
var button = document.getElementById("reactionTester");
var start = document.getElementById("start");
var startTime;
var scoreContainer = document.getElementById("p");
var css = document.createElement("style");
css.type = "text/css";
var counter = 0;
function init() {
var startInterval /*in milliseconds*/ = Math.floor(Math.random() * 10) * 1000;
setTimeout(startTimer, startInterval);
}
function startTimer() {
startTime = Date.now();
document.body.appendChild(css);
css.innerHTML = "html{background-color: red;}";
if (counter = 1) {
p1 = document.getElementsByTagName('p')[0];
p1.parentNode.removeChild(p1);
}
}
function stopTimer() {
if (startTime) {
var stopTime = Date.now();
var dif = stopTime - startTime;
alert("Your time is " + dif + " ms");
startTime = null;
css.innerHTML = null;
var p = document.createElement("p");
document.body.appendChild(p);
p.innerHTML = dif;
counter = 0;
counter++;
} else {
alert("don't trick me");
}
}
</script>
</head>
<body>
<form id="form">
<div class="tableRow">
<input type="button" value="start" id="start" onclick="init()">
</div>
<div class="tableRow">
<input type="button" id="reactionTester" onclick="stopTimer()" value="stop">
</div>
<div id="p">
</div>
</form>
</body>
</html>
There are 2 (potential) problems here:
Every time init() is run it resets startTime to Date.now(). So when stopTimer runs, it runs only against the latest click time.
init can set an interval of 0ms which may be intended...
To fix the first problem you can do one of a few things, but the most straightforward is to cancel the first timeout by getting a reference then later clearing it:
var timeoutId;
function init(){
if (timeout) clearTimeout(timeoutId);
timeoutId = setTimeout(func, delay);
}
You need to keep track of the timers in a variable so you can reset it.
<!DOCTYPE html>
<html>
<head>
<script>
var button = document.getElementById("reactionTester");
var start = document.getElementById("start");
var startTime;
var scoreContainer = document.getElementById("p");
var css = document.createElement("style");
css.type = "text/css";
var counter = 0;
var timer = null;
function init() {
var startInterval /*in milliseconds*/ = Math.floor(Math.random() * 10) * 1000;
clearTimeout(timer);
timer = setTimeout(startTimer, startInterval);
}
function startTimer() {
startTime = Date.now();
document.body.appendChild(css);
css.innerHTML = "html{background-color: red;}";
if (counter = 1) {
p1 = document.getElementsByTagName('p')[0];
p1.parentNode.removeChild(p1);
}
}
function stopTimer() {
if (startTime) {
var stopTime = Date.now();
var dif = stopTime - startTime;
alert("Your time is " + dif + " ms");
startTime = null;
css.innerHTML = null;
var p = document.createElement("p");
document.body.appendChild(p);
p.innerHTML = dif;
counter = 0;
counter++;
} else {
alert("don't trick me");
}
}
</script>
</head>
<body>
<form id="form">
<div class="tableRow">
<input type="button" value="start" id="start" onclick="init()">
</div>
<div class="tableRow">
<input type="button" id="reactionTester" onclick="stopTimer()" value="stop">
</div>
<div id="p">
</div>
</form>
</body>
</html>

Adding start, stop, and reset buttons for a timer

I'm making a timer and have it working already one load. I want to add a start, stop, and reset button to it. This is my code as is atm.
(function() {
"use strict";
var secondsLabel = document.getElementById('seconds'),
minutesLabel = document.getElementById('minutes'),
hoursLabel = document.getElementById('hours'),
totalSeconds = 0,
startButton = document.getElementById('start'),
resetButton = document.getElementById('reset'),
onOff = 0;
startButton.onclick = function() {
onOff = 1;
};
resetButton.onclick = function() {
totalSeconds = 0;
onOff = 0;
};
if ( onOff == 1 ) {
setInterval( setTime, 1000 );
function setTime() {
totalSeconds++;
secondsLabel.innerHTML = pad( totalSeconds % 60 );
minutesLabel.innerHTML = pad( parseInt( totalSeconds / 60 ) );
hoursLabel.innerHTML = pad( parseInt( totalSeconds / 3600 ) )
}
function pad( val ) {
var valString = val + "";
if( valString.length < 2 ) {
return "0" + valString;
} else {
return valString;
}
}
}
})();
The buttons are not working atm however. I'm not sure if this the best solution for the goal as well, so suggestions are welcome.
(function() {
"use strict";
var secondsLabel = document.getElementById('seconds'), minutesLabel = document.getElementById('minutes'), hoursLabel = document
.getElementById('hours'), totalSeconds = 0, startButton = document.getElementById('start'), stopButton = document.getElementById('stop'), resetButton = document
.getElementById('reset'), timer = null;
startButton.onclick = function() {
if (!timer) {
timer = setInterval(setTime, 1000);
}
};
stopButton.onclick = function() {
if (timer) {
clearInterval(timer);
timer = null;
}
};
resetButton.onclick = function() {
if (timer) {
totalSeconds = 0;
stop();
}
};
function setTime() {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
hoursLabel.innerHTML = pad(parseInt(totalSeconds / 3600))
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
})();
<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;
function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()" />
<input type="text" id="txt" />
<input type="button" value="Stop count!" onclick="stopCount()" />
</form>
<p>
Click on the "Start count!" button above to start the timer. The input field will count forever, starting at 0. Click on the "Stop count!" button to stop the counting. Click on the "Start count!" button to start the timer again.
</p>
</body>
</html>

Categories