setInterval and clearInterval through button click events - javascript

Here is my code:
window.onload = runThis;
function runThis() {
const txtMin = document.getElementsByClassName("min");
const txtSec = document.getElementsByClassName("sec");
function go() {
setInterval(countDown, 1000);
}
function countDown() {
timeNow = timeNow - 1;
timeSec = timeNow % 60; //remainder as seconds
timeMin = Math.round((timeNow/60) - (timeSec/60)); //minutes
txtMin[0].innerText =
(timeMin > 0 ?
(timeMin >= 10 ? `${timeMin}:` : `0${timeMin}:`)
: "00:");
txtSec[0].innerText =
(timeSec > 0 ?
(timeSec >= 10 ? timeSec : `0${timeSec}`)
: "00");
}
function stopIt() {
let x = setInterval(countDown, 1000);
clearInterval(x);
}
const btnStart = document.getElementsByClassName("start");
btnStart[0].addEventListener("click", go);
const btnStop = document.getElementsByClassName("stop");
btnStop[0].addEventListener("click", stopIt);
}
I am having trouble trying to set up setInterval and clearInterval.
2 buttons: start and stop. I want the function go to run when I click start to start the timer. That is all good. My problem is trying to stop the timer.
If I put let x = setInterval(countDown, 1000); outside the stopIt() function, it will automatically start the timer on windows.onload regardless of whether or not I click the start button but, in doing so, I can stop the timer.
If I put let x = setInterval(countDown, 1000); inside the stopIt() function like what I have here, I can start the timer whenever I want by clicking the start button, but now I can't stop the timer using clearInterval().
Any help is greatly appreciated. Thanks in advance!

Try to set the ID of the interval in the "go" function in a variable outside to be canceled inside the "stopIt" function, like this:
window.onload = runThis;
function runThis() {
var intervalID = null;
const txtMin = document.getElementsByClassName("min");
const txtSec = document.getElementsByClassName("sec");
function go() {
intervalID = setInterval(countDown, 1000);
}
function countDown() {
timeNow = timeNow - 1;
timeSec = timeNow % 60; //remainder as seconds
timeMin = Math.round((timeNow/60) - (timeSec/60)); //minutes
txtMin[0].innerText =
(timeMin > 0 ?
(timeMin >= 10 ? `${timeMin}:` : `0${timeMin}:`)
: "00:");
txtSec[0].innerText =
(timeSec > 0 ?
(timeSec >= 10 ? timeSec : `0${timeSec}`)
: "00");
}
function stopIt() {
clearInterval(intervalID);
}
const btnStart = document.getElementsByClassName("start");
btnStart[0].addEventListener("click", go);
const btnStop = document.getElementsByClassName("stop");
btnStop[0].addEventListener("click", stopIt);
}

Related

What's the best was to addEventListener onclick to the timer that I already have in place?

Apologies for the beginner question, I'm brushing up on my JS and this is my first post on here. I'm trying to add an event listener to this JS timer that's connected to my button .start-timer. What's the best way to go about it? Any help is appreciated, thanks!
const timeH = document.querySelector('h2');
let timeSecond = 30;
timeH.innerHTML = `${timeSecond}`;
const countdown = setInterval (()=>{
timeSecond --;
timeH.innerHTML = `${timeSecond}`;
if(timeSecond <= 0 || timeSecond < 1){
clearInterval(countdown);
}
},1000)
Make 2 functions to start and stop which only setInterval or clearInterval nothing special.
const timeH = document.querySelector('h2');
let timeSecond = 30;
timeH.innerHTML = `${timeSecond}`;
var countdown;
function start() {
clearInterval(countdown);
countdown = setInterval(() => {
timeSecond -= 0.1;
timeH.innerHTML = `${timeSecond.toFixed(1)}`;
if (timeSecond <= 0 || timeSecond < 1) {
clearInterval(countdown);
}
}, 100)
}
function stop() {
clearInterval(countdown);
}
document.querySelector(".start-timer").addEventListener('click', start);
document.querySelector(".stop-timer").addEventListener('click', stop);
<h2>hello</h2>
<button class="start-timer">start-timer</button>
<button class="stop-timer">stop-timer</button>

Javascript Stopwatch. Need help to store my timer and when page refresh to keep the time and continue from there

I have a working stopwatch. When I click start button the stopwatch is starting and when I click pause button the stopwatch is paused. What I would like is when I refresh my browser to keep the current time of the stopwatch and continue from there with the same functionality. Or when I echo the stopwatch time from a database to continue from the exact time it was before is saved it.
let showTime = document.querySelector("#output");
let startTimeButton = document.querySelector("#start")
let pauseTimeButton = document.querySelector("#pause")
pauseTimeButton.style.display = "none";
let seconds = 0;
let interval = null;
const timer = () => {
seconds++;
// Get hours
let hours = Math.floor(seconds / 3600);
// Get minutes
let minutes = Math.floor((seconds - hours * 3600) / 60);
// Get seconds
let secs = Math.floor(seconds % 60);
if (hours < 10) {
hours = `0${hours}`;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (secs < 10) {
secs = `0${secs}`;
}
showTime.innerHTML = `${hours}:${minutes}:${secs}`;
};
startTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "block";
startTimeButton.style.display = "none";
console.log("START TIME CLICKED");
if (interval) {
return;
}
interval = setInterval(timer, 1000);
});
// Pause function
pauseTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "none";
startTimeButton.style.display = "block";
console.log("PAUSE TIME CLICKED");
clearInterval(interval);
interval = null;
});
<button id="start">Start</button>
<button id="pause">Pause</button>
<div id="output"></div>
You could use localStorage.
In order to save each second passed you could modify your timer function to save to localStorage:
let seconds = 0;
if (localStorage.getItem("stopwatchSeconds") != null) {
seconds = parseInt(localStorage.getItem("stopwatchSeconds"));
}
//...
const timer = () => {
//...
seconds++;
localStorage.setItem("stopwatchSeconds", seconds);
//...
};
//...
I hope this helps.
It seems like what you're looking for is localStorage. You store your stopwatch data, such as startAt, totalSeconds in the storage and when you refresh the page you can restore your stopwatch state based on the saved data: remainingTime = (startAt + totalSeconds) - currentTime
localStorage docs: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage#storing_simple_data_%E2%80%94_web_storage

JavaScript Local Storage Second Counter

my question is the following: Is it possible to create a second counter using local storage? I mean you load the page, the counter starts counting from 1 one by one. You reload the page at 5seconds, and the counter won't resets but continues the counting from 5. Is it possible?
I have a code with a simple sec counter, but I don't know how to make it workable with Local Storage
var seconds = 0;
var el = document.getElementById('seconds-counter');
function incrementSeconds() {
seconds += 1;
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
<div id='seconds-counter'> </div>
this way ?
<div id="seconds-counter">_</div>
<!-- button id="bt-stop-counter"> stop counter </button -->
const
counterLimit = 5 // <-- your counter limit value....
, div_s_counter = document.querySelector('#seconds-counter')
, btStopCounter = document.querySelector('#bt-stop-counter')
, timeRef_ls = localStorage.getItem('counterVal') || 0
, timeRef = (new Date()) - (timeRef_ls * 1000)
, CounterIntv = setInterval(() =>
{
let seconds = Math.floor(((new Date()) - timeRef) / 1000)
if (seconds >= counterLimit ) // stopCounter()
{
div_s_counter.textContent = seconds = counterLimit
clearInterval( CounterIntv )
}
div_s_counter.textContent = seconds
localStorage.setItem('counterVal', seconds.toString(10))
}
, 500)
;
div_s_counter.textContent = timeRef_ls
/* disable counter reset ------------------------------------
{
clearInterval( CounterIntv ) // to stop the counter
localStorage.removeItem('counterVal') // remove the counter
}
btStopCounter.onclick = stopCounter
------------------------------------------------------------*/
var el = document.getElementById('seconds-counter');
function incrementSeconds() {
var counter = window.localStorage.getItem("counter") ?? 0;
window.localStorage.setItem("counter", ++counter);
el.innerText = counter;
}
var cancel = setInterval(incrementSeconds, 1000);

Pause/Continue in Pomodoro Timer project

I am building a pomodoro tracker in order to practice a little bit of JavaScript. It's been a while since I started this project. After this particulary problem which is implement a pause/continue functionality I abandoned the project. I really got stucked. I know programming is not easy and I will be facing many problems in the future but I really can't figure out how to solve this task. I am feeling stupid
Here is the JavaScript code:
// General Variables
let display = document.querySelector('.display');
// is the timer paused?
// let isPaused = true;
// let count = 0;
//const playPomodoro = document.querySelector('.play');
const pause = document.querySelector('.pause');
const resume = document.querySelector('.resume');
const stopPomodoro = document.querySelector('.stop');
const pomodoro = document.querySelector('#pomodoro');
const shortBreak = document.querySelector('#shortbreak');
const longBreak = document.querySelector('#longbreak')
const audioBeep = document.querySelector('#audioBeep');
const twentyFiveMinutes = 60 * 25;
const fiveMinutes = 60 * 5;
const thirtyMinutes = 60 * 30;
// Start Pomodoro timer 25 minutes
pomodoro.addEventListener('click', () => {
startTimer(twentyFiveMinutes, display);
stopClick(shortBreak, longBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Start Pomodoro short break
shortBreak.addEventListener('click', () => {
startTimer(fiveMinutes, display);
stopClick(pomodoro, longBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Start Pomodoro Long break
longBreak.addEventListener('click', () => {
startTimer(thirtyMinutes, display);
stopClick(pomodoro, shortBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Stopping Clicks Events
function stopClick(btn1, btn2) {
btn1.classList.add('avoid-clicks');
btn2.classList.add('avoid-clicks');
}
// Remove .avoid-clicks class
function removeAvoidClick(btn1, btn2, btn3) {
btn1.classList.remove('avoid-clicks');
btn2.classList.remove('avoid-clicks');
btn3.classList.remove('avoid-clicks');
}
// main start timer function
function startTimer(duration, display) {
let timer = duration, min, sec;
let countingDown = setInterval(function() {
min = parseInt(timer / 60, 10);
sec = parseInt(timer % 60, 10);
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
display.innerHTML = min + ":" + sec;
if (--timer < 0) {
timer = duration;
}
// stops the counting variable when it hits zero
if (timer == 0) {
clearInterval(countingDown);
display.innerHTML = "00:00";
audioBeep.play();
removeAvoidClick(pomodoro,shortBreak,longBreak);
}
// Pause the clock
pause.addEventListener('click', () => {
});
// Stop the counter and set it to 00:00 when the user clicks the stop button
stopPomodoro.addEventListener('click', () => {
clearInterval(countingDown);
display.innerHTML = "00:00";
removeAvoidClick(pomodoro,shortBreak,longBreak);
});
}, 1000);
}
I will store the timer status in an object, then you activate a timer that decreses the current time left and call UI update.
let timer = {
timeLeft: 0,
running: 0,
};
function startTimer(duration) {
timer.timeLeft = duration;
if (!timer.run) {
timer.run = true;
run();
}
}
function run() {
if (timer.run) {
timer.timeLeft -= 1;
setTimeout(run, 1000)
}
}
function pauseTimer() {
timer.run = false;
}
function resumeTimer() {
if (!timer.run) {
timer.run = true;
run();
}
update();
}
function update() {
// everything you need to update in the UI from the timer object
}

How to stop countdown after a few rounds?

var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
setTimeout(timer,2000);
}
timer();
setInterval(timer, 17000);
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<p id="seconds">15</p>
<button id= "btnSurrender">end now</button>
</body>
</html>
I need help with my little problem. I made a stopwatch which counts down 15 seconds. After this 15 seconds, it waits two seconds and starts again. You have option to stop counting when you want to, using "end now" button (then it'll start again after 2 sec). Now, my question is: how can I make a function which is going to stop whole counting after 3/4 rounds?
You restart the clock in surrender() using the call setTimeout(timer, 2000). All you need to do is add an if statement inside that function testing a variable that controls how many times you have run the timer, and then call/not call timer() accordingly. Here is a working example of it: https://jsfiddle.net/L38q6k5d/, but just to give you an idea of how it would work:
At the top of the js file:
var timesRun = 0
var timerInterval = null;
Inside the surrender function:
timesRun += 1 // Increment it each time the timer ends
if (timesRun > 4) { // If the timer has run less than 4 times
return; // this will stop the function here, so we dont start the timer again
}
setTimeout(timer, 2000); // Reset the timer
Inside the timer function,
if (timesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
When starting the initial timer:
timer();
timerInterval = setInterval(timer, 17000);
Complete JS:
var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
var timerInterval = null;
// New Code
var numberOfTimesRun = 0; // this is where we keep track of how many times the timer has run
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
// New Code
if (numberOfTimesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
// End New Code
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
numberOfTimesRun += 1; // so we know that 1 iteration of the timer has been completed
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
//New Code
numberOfTimesRun += 1;
if (numberOfTimesRun > 4) {
return; // end the function there
}
setTimeout(timer, 2000)
//End New Code
}
timer();
timerInterval = setInterval(timer, 17000);

Categories