Pausing Javascript Timer - javascript

How to pause this timer? And if it's paused how to unpause and continue counting? It should be a function
function timer($time) {
let $lorem = $("#lorem");
function countdown() {
let $minutes = Math.floor($time / 60);
let $seconds = $time % 60;
let $result = $minutes + ":" + ($seconds < 10 ? "0" + $seconds : $seconds);
--$time;
$lorem.text($result);
}
countdown();
setInterval(countdown, 1000);
}
timer(200);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lorem"></div>

You can do this by storing the result of setInterval in a variable:
var timeKeeper = setInterval(countdown, 1000);
Then when you want to pause, use clearInterval:
clearInterval(timeKeeper);
This will stop the interval from executing. To start again, reset the timer variable:
timeKeeper= setInterval(countdown, 1000);

Use a flag pause with a click event, on click toogle pause:
let pause = false;
$lorem.on('click', function() {
pause = !pause;
});
Then check if !pause and time > 0 then reduce the time by 0.1s
If the time <= 0 to remove the interval just call clearInterval(setInt) (note you need to define it first like let setInt = setInterval(countdown, 100);)
Using 100ms because better precision when you pause, otherwise after a click, your clock still gonna run into next sec then stop.
If !pause then $time = $time - 0.1; continue. Otherwise keep the same time and pass to next call.
function timer($time) {
let $lorem = $("#lorem");
let pause = false;
let setInt = setInterval(countdown, 100);
$('#pause').on('click', function() {
pause = !pause;
});
function countdown() {
if (!pause && $time > 0) {
$time = ($time - 0.1).toFixed(1);
}
if($time <= 0){
clearInterval(setInt);
}
let $minutes = Math.floor($time / 60);
let $seconds = Math.ceil($time % 60);
let $result = $minutes + ":" + ($seconds < 10 ? "0" + $seconds : $seconds);
$lorem.text($result);
console.log($time);
}
}
timer(3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lorem"></div>
<br>
<button id="pause">Pause</button>

Related

How to end my countdown timer when a button is clicked?

I'm trying to create a function that will end a countdown timer, or automatically make the minutes and seconds part of the countdown timer === 0; however, it seems that using clearInterval(time) doesn't seem to work! Could anyone point out how I might be able to achieve what I'm trying to do!
Note that I've made startingMinutes = 1 just for my ease.
Below is the countdown function and HTML:
// FUNCTION - countDown function that counts down from 8 minutes
const startingMinutes = 1;
let time = startingMinutes * 60;
function updateCountDown() {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 1 ? '0' + seconds : seconds;
document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (minutes == 0 && seconds == 0) {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
//my attempt at clearing the countdowntimer!
window.addEventListener('DOMContentLoaded', function() {
document.getElementById("submit_button").addEventListener("click", function() {
clearInterval(time);
})});
HTML:
//where the countdown timer is displayed
<div id="circle"><p id="countdown">8:00</p></div>
//Click the below button and the countdown timer will end (minutes === 0 and seconds === 0)
<button id="submit_button" type="submit">Click to Submit</button>
To use clearInterval you need to pass it the value returned by setInterval
I have an example below using your code, where I pass the value from "setInterval" which I call "interval" to a function "stop" which calls "clearInterval" to stop the timer, and runs the code you were running.
let isListening = true;
const recognition = { abort: () => console.log('aborted') };
function updateCountDown(time) {
const minutes = Math.floor(time / 60);
const seconds = time % 60;
const timer = document.getElementById("countdown");
timer.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
function start(time) {
const interval = setInterval(() => {
if (--time) updateCountDown(time);
else stop(interval);
}, 1000);
document.getElementById("submit_button")
.addEventListener("click", () => stop(interval))
}
function stop(interval) {
updateCountDown(0); // This line sets time to 0
clearInterval(interval);
foo()
}
// I assume you want this to happen when the timer runs down or the button is clicked
function foo() {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
start(8*60)
#tableStyle, #wordsIncluded, #show_header_one { display: none; }
<p id="tableStyle">Table Style</p>
<p id="wordsIncluded">Words Included</p>
<p id="show_header_one">Show Header One</p>
<div id="circle">
<p id="countdown">8:00</p>
</div>
<button id="submit_button" type="submit">Click to Submit</button>
const startingMinutes = 1;
let time = startingMinutes * 60;
var abort_count_down = true;
function updateCountDown() {
if (abort_count_down) {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 1 ? '0' + seconds : seconds;
document.getElementById("countdown").innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (minutes == 0 && seconds == 0) {
document.getElementById('tableStyle').style.display = "block";
document.getElementById('wordsIncluded').style.display = "block";
document.getElementById('show_header_one').style.display = "block";
recognition.abort(); //speech recognition stops when countdown timer ends
isListening = false;
}
};
//my attempt at clearing the countdowntimer!
window.addEventListener('DOMContentLoaded', function() {
document.getElementById("submit_button").addEventListener("click", function() {
abort_count_down = false;
})});

Why is Javascript clearInterval not working on button click?

I have a timer program that counts down from 25:00 on "start" button click and is supposed to reset and clearInterval() on "reset" button click. When the timer reaches 0:00 the if statements all pass and resetTimer() is called which executes the clearInterval() which works in this instance. So in short: clearInterval() works when the if statements pass but not when I click the "reset" button. Can someone please explain to me why this is happening and offer a solution? Thank you!
//My Programs Code:
//Timer Widget
function timerStartReset(event) {
var minutes;
var seconds;
//decrease minutes html every minute
const minutesInterval = setInterval(() => {
minutes -= 1;
timerMinute.innerHTML = minutes;
}, 60000);
//decrease seconds html every second
const secondsInterval = setInterval(() => {
seconds -= 1;
timerSeconds.innerHTML = seconds < 10 ? `0${seconds}` : seconds;
//check if timer reaches 00:00
if (seconds <= 0) {
if (minutes <= 0) {
//stop and reset timer
//**HERE resetTimer() is called and clearInterval works**
resetTimer();
//return start button functionality
timerStartBtn.disabled = false;
//add a star
const addStar = `<i class="fas fa-star h2 mx-2"></i>`;
timerStarContainer.insertAdjacentHTML("beforeend", addStar);
localStorage.setItem("timer stars", timerStarContainer.innerHTML);
setTimeout(breakAlert, 1000);
}
seconds = 60;
}
}, 1000);
//start button function
if (event.target.id === "timer-start") {
startTimer();
event.target.disabled = true;
}
//reset button function
else {
//**HERE resetTimer() is called but clearInterval doesn't work**
resetTimer();
timerStartBtn.disabled = false;
}
//Reset timer
function resetTimer() {
//Reset to starting template
timerMinute.innerHTML = 25;
timerSeconds.innerHTML = "00";
//Clear minute/second timeout function
clearInterval(minutesInterval);
clearInterval(secondsInterval);
}
//start timer
function startTimer() {
//Change starting time and add them to page
minutes = 0;
seconds = 1;
timerMinute.innerHTML = minutes;
timerSeconds.innerHTML = seconds;
//start countdown
minutesInterval;
secondsInterval;
}
//Alert for breaks
function breakAlert() {
//If 4 star divs are added dynamically
if (timerStarContainer.childElementCount >= 4) {
swal(
"Great Job! You Did It!",
"Go ahead and take a 15-30 minute break!",
"success"
);
//remove all stars from DOM
timerStarContainer.innerHTML = "";
} else {
swal("Awesome!", "Please take a 5 minute break!", "success");
}
}
}
//End Timer Widget
const timerMinute = document.querySelector("#minute");
const timerSeconds = document.querySelector("#seconds");
const timerStartBtn = document.querySelector("#timer-start");
document.querySelector("#timer-btns").addEventListener("click", timerStartReset);
//Timer Widget
function timerStartReset(event) {
var minutes;
var seconds;
//decrease minutes html every minute
const minutesInterval = setInterval(() => {
minutes -= 1;
timerMinute.innerHTML = minutes;
}, 60000);
//decrease seconds html every second
const secondsInterval = setInterval(() => {
seconds -= 1;
timerSeconds.innerHTML = seconds < 10 ? `0${seconds}` : seconds;
//check if timer reaches 00:00
if (seconds <= 0) {
if (minutes <= 0) {
//stop and reset timer
resetTimer();
//return start button functionality
timerStartBtn.disabled = false;
}
seconds = 60;
}
}, 1000);
//start button function
if (event.target.id === "timer-start") {
startTimer();
event.target.disabled = true;
}
//reset button function
else {
resetTimer();
timerStartBtn.disabled = false;
}
//Reset timer
function resetTimer() {
//Reset to starting template
timerMinute.innerHTML = 0;
timerSeconds.innerHTML = 11;
//Clear minute/second timeout function
clearInterval(minutesInterval);
clearInterval(secondsInterval);
console.log("reset");
}
//start timer
function startTimer() {
//Change starting time and add them to page
minutes = 0;
seconds = 10;
timerMinute.innerHTML = minutes;
timerSeconds.innerHTML = seconds;
//start countdown
minutesInterval;
secondsInterval;
}
}
//End Timer Widget
<!-- Timer -->
<div>
<span id="minute">0</span>
<span>:</span>
<span id="seconds">11</span>
</div>
<div id="timer-btns">
<button id="timer-start">Start</button>
<button id="timer-reset">Reset</button>
</div>
<!-- End Timer -->
The variables minutesInterval and secondsInterval are local to this function. So every time you call the function, it starts new timers and creates new variables. When the code calls resetTimer(), it's only resetting the timer started by that invocation of timerStartReset, not the previous ones.
It works when the timer runs out, because the countdown code is in the same scope. But when you click the Reset button, that function is a new scope and can't access the variables from when the Start button was clicked.
The timer variables should be global variables that can be accessed from any invocation. And then there's no reason to use the same function for both buttons.
var minutesInterval;
var secondsInterval;
timerStartBtn.addEventListener('click', timerStart);
timerResetBtn.addEventListener('click', resetTimer);
function timerStart() {
resetTimer();
var minutes;
var seconds;
//decrease minutes html every minute
minutesInterval = setInterval(() => {
minutes -= 1;
timerMinute.innerHTML = minutes;
}, 60000);
//decrease seconds html every second
secondsInterval = setInterval(() => {
seconds -= 1;
timerSeconds.innerHTML = seconds < 10 ? `0${seconds}` : seconds;
//check if timer reaches 00:00
if (seconds <= 0) {
if (minutes <= 0) {
resetTimer();
//return start button functionality
timerStartBtn.disabled = false;
//add a star
const addStar = `<i class="fas fa-star h2 mx-2"></i>`;
timerStarContainer.insertAdjacentHTML("beforeend", addStar);
localStorage.setItem("timer stars", timerStarContainer.innerHTML);
setTimeout(breakAlert, 1000);
}
seconds = 60;
}
}, 1000);
startTimer();
//start timer
function startTimer() {
//Change starting time and add them to page
minutes = 0;
seconds = 1;
timerMinute.innerHTML = minutes;
timerSeconds.innerHTML = seconds;
//start countdown
minutesInterval;
secondsInterval;
}
//Alert for breaks
function breakAlert() {
//If 4 star divs are added dynamically
if (timerStarContainer.childElementCount >= 4) {
swal(
"Great Job! You Did It!",
"Go ahead and take a 15-30 minute break!",
"success"
);
//remove all stars from DOM
timerStarContainer.innerHTML = "";
} else {
swal("Awesome!", "Please take a 5 minute break!", "success");
}
}
}
//Reset timer
function resetTimer() {
//Reset to starting template
timerMinute.innerHTML = 25;
timerSeconds.innerHTML = "00";
//Clear minute/second timeout function
clearInterval(minutesInterval);
clearInterval(secondsInterval);
}
//End Timer Widget

How to make a pause/play button for timer on Javascript?

I am trying to make my pause and play button function on javascript, but I don't exactly know the logic behind all of it
I have tried putting the clearInterval() method in my pauseTimer function
var startButton = document.getElementById("start");
var startSound = document.getElementById("audio");
var timerSound = document.getElementById("timer");
var counter = document.getElementById("counter");
var middlebuttons = document.getElementsByClassName("middlebuttons");
var pauseButton = document.getElementById("pause");
var playButton = document.getElementById('play');
function pauseTimer(){
clearInterval();
alert("Pause button");
}
function playTimer(){
alert("Play button");
}
function countDown(minutes){
var seconds = 60;
var mins = minutes;
function tick(){
var current_minutes = mins - 1;
seconds --;
counter.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if(seconds > 0){
setTimeout(tick, 10);
} else {
if(mins > 1){
countDown(mins - 1);
}
else if (mins && seconds === 0 ){
timerSound.play();
buttons();
}
}
}
tick();
}
pauseButton.addEventListener('click', pauseTimer, playAudio );
playButton.addEventListener('click', playTimer, playAudio );
Here's a thoroughly commented suggested solution. It uses a totalSeconds variable as the counter's source of truth.
The reason the timer variable is needed is because clearInterval wants to be told which interval to clear.
There's no "stop" button in this demo. If you want to reset the timer while it's running, just refresh the page.
(And it doesn't include any functions to play sounds, but you could add those at the appropriate points in the code.)
// Defines identifiers for accessing HTML elements
const minutesInput = document.getElementById("minutesInput"),
startButton = document.getElementById("startButton"),
pauseButton = document.getElementById("pauseButton"),
unpauseButton = document.getElementById("unpauseButton"),
counterDiv = document.getElementById("counterDisplay");
// Adds listeners and declares global variables
startButton.addEventListener('click', start);
pauseButton.addEventListener('click', pauseTimer);
unpauseButton.addEventListener('click', runTimer);
let totalSeconds; // global variable to count down total seconds
let timer; // global variable for setInterval and clearInterval
//Disables buttons that are not needed yet
disable(pauseButton);
disable(unpauseButton);
// Defines functions that get the minutes and seconds for display
function getMinutes(totalSeconds){
return Math.floor(totalSeconds / 60); // Gets quotient rounded down
}
function getSeconds(totalSeconds){
let seconds = totalSeconds % 60; // Gets remainder after division
return (seconds < 10 ? "0" + seconds : seconds) // Inserts "0" if needed
}
// Defines functions that manipulate the countdown
function start(){
totalSeconds = minutesInput.value * 60; // Sets initial value of totalSeconds based on user input
counterDiv.innerHTML = getMinutes(totalSeconds) + ":" + getSeconds(totalSeconds); // Initializes display
disable(minutesInput); disable(startButton); // Toggles buttons
runTimer();
}
function runTimer(){
// Is the main timer function, calls `tick` every 1000 milliseconds
timer = setInterval(tick, 1000);
disable(unpauseButton); enable(pauseButton); // Toggles buttons
}
function tick(){
if(totalSeconds > 0){
totalSeconds--; // Decreases total seconds by one
counterDiv.innerHTML = getMinutes(totalSeconds) + ":" + getSeconds(totalSeconds); // Updates display
}
else{
// The timer has reached zero. Let the user start again.
enable(minutesInput); enable(startButton);
disable(pauseButton); disable(unpauseButton);
}
}
function pauseTimer(){
// Stops calling `tick` and toggles buttons
clearInterval(timer);
disable(pauseButton); enable(unpauseButton);
}
// Defines functions to disable and re-enable HTML elements
function disable(element){ element.setAttribute("disabled",""); }
function enable(element){ element.removeAttribute("disabled"); }
counter{ height: 1em; width: 2em; margin: 0.4em; border: 1px solid grey }
<label>
How many minutes?:
<input type="number" id="minutesInput" value="1" />
</label>
<br />
<button id="startButton">Start</button>
<button id="pauseButton">Pause</button>
<button id="unpauseButton">Continue</button>
<div id="counterDisplay"></div>

how to create click event to display set interval time

I have a Javascript setInterval function set up to display like a timer. I'd like to display the time that is on the timer when a "next" button is clicked so the user can see how long they've spent on a certain page. I'm unsure how to connect the setInterval with a click event. This is what I have, but it's not working.
let timerId = setInterval(function () {
document.getElementById("seconds").innerHTML = pad(++sec % 60);
document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);
function myFunction() {
alert document.getElementById("timerId").innerHTML = "Time passed: " + timerId);
}
This should solve your problem.
var initialTime = new Date().getTime();
var timeSpent='0:00';
var timeElement = document.getElementById("time");
timeElement.innerHTML = timeSpent;
let timerId = setInterval(function () {
var currentTime = new Date().getTime();
timeSpent = millisToMinutesAndSeconds(currentTime - initialTime)
timeElement.innerHTML = timeSpent;
}, 1000);
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
function alertFn(){alert(timeSpent)}
document.getElementById("rightButton").addEventListener('click',alertFn);
document.getElementById("wrongButton").addEventListener('click',alertFn);
<h1 id="time"></h1>
<button id="rightButton">Right</button>
<button id="wrongButton">Wrong</button>
First of all, it would be better if you put setInterval method inside the function. After that you could give your function to an event listener as an argument.
Your code should look something like this
let timerId;
function displayTime() {
timerId = setInterval(() => {
// your code
}, 1000);
}
document.querySelector('button').addEventListener('click', displayTime)

Timer keeps getting faster on every reset

The timer keeps getting faster every time I reset it. I'm thinking I need to use clearTimeout but am unsure about how to implement it. Here's the code:
$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function() {
timeInSeconds = sessionmin * 60;
timeout();
});
})
function timeout(){
setTimeout(function () {
if (timeInSeconds > 0) {
timeInSeconds -= 1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours*3600)/60);
seconds = Math.floor(timeInSeconds - hours*3600 - minutes*60);
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}
You have to define your setTimeout as a variable to reset it.
See Fiddle
var thisTimer; // Variable declaration.
$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function(){
clearTimeout(thisTimer); // Clear previous timeout
timeInSeconds = sessionmin * 60;
timeout();
});
})
function timeout(){
thisTimer = setTimeout(function () { // define a timeout into a variable
if(timeInSeconds>0){
timeInSeconds-=1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}
You should: use setInterval instead of setTimeout, return the interval id that setInterval generates, clear that interval before you restart it. Here is an example: https://jsfiddle.net/8n2b7x0s/
$(function(){
var sessionmin = 25;
var intervalId = null;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function() {
timeInSeconds = sessionmin * 60;
// clear the current interval so your code isn't running multiple times
clearInterval(intervalId);
// restart the timer
intervalId = run();
});
})
function run(){
return setInterval(function () {
if(timeInSeconds>0){
timeInSeconds-=1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
}, 1000);
}

Categories

Resources