How to pause and resume timer in JavaScript? - javascript

I've been trying to create my own "pomodoro" like timer and got stuck when trying to pause and pause and resume the timer. I want my timer to start at 40:00, it currently runs when the "Start" button is pressed and stops when I press a "Stop" button, but it doesn't resume when I press the "Start" button again.
var startButton = document.getElementById("startButton");
var stopButton = document.getElementById("stopButton");
var resetButton = document.getElementById("resetButton");
var isRunning = false;
startButton.addEventListener("click", function () {
trigger();
});
stopButton.addEventListener("click", function () {
stopTimer();
});
resetButton.addEventListener("click", function() {
resetTimer();
});
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
if (isRunning === false) {
isRunning = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
timer--;
}, 1000);
} else {
isRunning = !isRunning;
}
if (timer < 0) {
clearInterval(isRunning);
}
};
function trigger() {
var fiveMinutes = 2400,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
function stopTimer() {
clearInterval(isRunning);
};
<div class="main-downwards-buttons">
<button id="startButton" type="button" class="btn-success">Start</button>
<button id="stopButton" type="button" class="btn-danger">Stop</button>
<button id="resetButton" type="button" class="btn-secondary">Reset</button>
</div>

Declare fiveMinutes in the global scope and reset it only when reset button is clicked.
And you need to update its value inside the anonymous function to keep it running. The issue here is that you can have only one counter.
var startButton = document.getElementById("startButton");
var stopButton = document.getElementById("stopButton");
var resetButton = document.getElementById("resetButton");
var isRunning = false;
var fiveMinutes = 2400;
var display = document.querySelector('#time');
startButton.addEventListener("click", function () {
startTimer(fiveMinutes, display);
});
stopButton.addEventListener("click", function () {
stopTimer();
});
resetButton.addEventListener("click", function() {
stopTimer();
fiveMinutes = 2400;
display.textContent = '0:00';
});
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
if (isRunning === false) {
isRunning = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
timer --;
// You need to update the original variable
fiveMinutes --;
}, 1000);
} else {
isRunning = !isRunning;
}
if (timer < 0) {
stopTimer();
}
};
function stopTimer() {
clearInterval(isRunning);
isRunning = false;
};
<div id="time">0:00</div>
<div class="main-downwards-buttons">
<button id="startButton" type="button" class="btn-success">Start</button>
<button id="stopButton" type="button" class="btn-danger">Stop</button>
<button id="resetButton" type="button" class="btn-secondary">Reset</button>
</div>

Related

Add minutes to dom countdown timer

I made a count down timer but would like to add extra minutes to it with a button.
I made a function to add 1 minute to the timer but i can't get it to add the minute. How would I achieve this?
I commented out the code since it breaks the rest of my code.
The add1Minute() function should add 1 minute to the timer when it isn't running.
I tried doing this by adding 1 to the variable and after that add it to the timer.
let countdown;
create();
function create() {
const mainDiv = document.createElement("div");
document.body.appendChild(mainDiv);
const timeDiv = document.createElement("div");
timeDiv.setAttribute("id", "timeText");
timeDiv.innerHTML = "25:00";
mainDiv.appendChild(timeDiv);
const startButton = document.createElement("button");
startButton.setAttribute("class", "button");
//startButton.addEventListener ("id", "startButton");
startButton.addEventListener("click", startTimer);
startButton.innerHTML = "start";
mainDiv.appendChild(startButton);
const restartButton = document.createElement("button");
restartButton.setAttribute("class", "button");
restartButton.addEventListener("click", restartTimer);
restartButton.innerHTML = "restart";
mainDiv.appendChild(restartButton);
/*
const minute1Button = document.createElement("button");
minute1Button.setAttribute("class", "button");
startButton.addEventListener ('click', add1Minute);
minute1Button.innerHTML = "+ 1 minute";
mainDiv.appendChild(minute1Button);
const minute10Button = document.createElement("button");
minute10Button.setAttribute("class", "button");
minute10Button.addEventListener ('click',add10Minute);
minute10Button.innerHTML = "+ 10 minutes";
mainDiv.appendChild(minute10Button);
*/
}
//startTimer()
function startTimer(sMin1) {
let sMin = 0.15;
function add1Minute(sMin) {
sMin + 1;
return sMin;
}
//if(sMin1 != null){
//sMin + sMin1;
//}
let time = sMin * 60;
countdown = setInterval(update, 1000);
function update() {
let min = Math.floor(time / 60);
let sec = time % 60;
sec = sec < 10 ? "0" + sec : sec;
timeText.innerHTML = min + ":" + sec;
time--;
min == 0 && sec == 0 ? clearInterval(countdown) : countdown;
}
}
//function add1Minute(sMin){
// sMin + 1;
// return sMin1;
//}
function add10Minute() {}
function restartTimer() {
clearInterval(countdown);
document.body.innerHTML = "";
create();
}
try:
let sMin = 0.15;
function add1Minute() {
if (!countdown) {
sMin += 1;
}
}
function startTimer() {
let time = sMin * 60;
countdown = setInterval(update, 1000);
function update() {
let min = Math.floor(time / 60);
let sec = time % 60;
sec = sec < 10 ? "0" + sec : sec;
timeText.innerHTML = min + ":" + sec;
time--;
min == 0 && sec == 0 ? clearInterval(countdown) : countdown;
}
}

creating a countdown timer in javascript with automatic reload

Three problems, my start button starts more than one timer at the same time instead of only once for multiple clicks to start. Second, my stop button doesn't work. and my reset button, changes the text but doesnt stop the timer. Here's my code:
function stopTimer(timer) {
clearInterval(timer);
}
function resetTimer(duration, display) {
var timer = duration,
minutes, seconds;
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
}
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
// Beep when counter reaches zero
if (--timer < 0) {
timer = duration;
var context = new AudioContext();
var oscillator = context.createOscillator();
oscillator.type = "sine";
oscillator.frequency.value = 800;
oscillator.connect(context.destination);
oscillator.start();
setTimeout(function() {
oscillator.stop();
}, 100);
}
}, 1000);
}
var time_in_seconds = 5;
display = document.querySelector('#time');
document.getElementById("start").addEventListener("click", function() {
startTimer(time_in_seconds, display);
});
document.getElementById("stop").addEventListener("click", function() {
stopTimer(timer);
});
document.getElementById("reset").addEventListener("click", function() {
resetTimer(time_in_seconds, display);
});
<html>
<body>
<div id="time">00:10</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
<script>
</script>
</body>
</html>
var duration = 5;
var timer_id = null;
var timer_seconds = duration;
var timer_active = 0;
var display = document.querySelector('#time');
function BeepOnce() {
timer_seconds = duration;
var context = new AudioContext();
var oscillator = context.createOscillator();
oscillator.type = "sine";
oscillator.frequency.value = 800;
oscillator.connect(context.destination);
oscillator.start();
setTimeout(function() {
oscillator.stop();
}, 100);
}
function UpdateDisplay() {
var minutes = parseInt(timer_seconds / 60, 10);
var seconds = parseInt(timer_seconds % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
}
function TimerReset() {
timer_seconds = duration;
timer_active = 1;
UpdateDisplay();
}
function TimerStart() {
timer_seconds = duration;
timer_active = 1;
UpdateDisplay();
}
function TimerStop() {
timer_active = 0;
/*clearInterval(timer_id);*/
}
function TimerInit() {
UpdateDisplay();
var fun1 = function() {
if (timer_active) {
// Beep at Zero Seconds
if (--timer_seconds < 0) {
BeepOnce();
TimerReset();
}
// Countdown
else {
UpdateDisplay();
}
}
}
//called timer every second
timer_id = setInterval(fun1, 1000);
}
TimerInit();
document.getElementById("start").addEventListener("click", function() {
TimerStart();
});
document.getElementById("stop").addEventListener("click", function() {
TimerStop();
});
document.getElementById("reset").addEventListener("click", function() {
TimerReset();
});
<html>
<body>
<div id="time">00:10</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button></body>
</html>

Count up timer to restart the timer once "OK" is clicked in alert box

let hour = 0;
let minute = 0;
let seconds = 0;
let pauseTime = null;
let start = [...document.cookie.matchAll(/([^;=]+)=([^;=]+)(;|$)/g)].filter(x => x[1].trim() == 'timer').map(x => Number(x[2].trim()))[0];
if(start != null) {
if(start > 0) start = new Date(start);
else if(start < 0) {
pauseTime = -start;
start = new Date(Date.now() + start); //+- = -
} else start = null;
} else start = null;
let intervalId = null;
function startTimer() {
let totalSeconds;
if(pauseTime) {
start = new Date(Date.now() - pauseTime);
totalSeconds = pauseTime;
return;
} else {
totalSeconds = Math.floor((Date.now() - start.getTime()) / 1000);
}
hour = Math.floor(totalSeconds /3600);
minute = Math.floor((totalSeconds - hour*3600)/60);
seconds = totalSeconds - (hour*3600 + minute*60);
document.getElementById("hour").innerHTML =hour;
document.getElementById("minute").innerHTML =minute;
document.getElementById("seconds").innerHTML =seconds;
}
if(start) intervalId = setInterval(startTimer, 1000);
document.getElementById('start-btn').addEventListener('click', () => {
if(pauseTime) {
pauseTime = null;
} else {
if(start) return;
start = new Date();
intervalId = setInterval(startTimer, 1000);
}
document.cookie = "timer=" + String(start.getTime());
})
document.getElementById('stop-btn').addEventListener('click', () => {
pauseTime = Date.now() - start.getTime();
document.cookie = "timer=" + String(-pauseTime);
alert("Timer is Currently paused. Press Okay to resume time.");
document.getElementById("start-btn").click();
});
document.getElementById('reset-btn').addEventListener('click', () => {
start = null;
document.cookie = "timer=null";
if(intervalId) clearInterval(intervalId);
document.getElementById("hour").innerHTML = '0';
document.getElementById("minute").innerHTML = '0';
document.getElementById("seconds").innerHTML = '0';
});
<button id="start-btn">Start</button>
<button id="stop-btn">Pause</button>
<button id="reset-btn">Reset</button>
I have a simple app that start, pauses and reset a timer when the appropriate button is clicked. What I am trying to do is create an alert box when the pause button is clicked and once someone clicks OK on the alert box, the timer starts again. I thought simply mimicking selecting the start button again would do this, but instead it starts the time like the pause never occurred. Any suggestion?

In Javascript, I'm using clearInterval() in a function/reset button - the timer resets, but keeps going

I've made a timer with setInterval():
var seconds = 0, minutes = 0;
var timer = document.querySelector("#timer");
var interval = null;
function beginTimer() {
var interval = setInterval(function(){
timer.innerHTML = minutes + " Minute(s) " + seconds + " Seconds";
seconds++;
if(seconds == 60) {
minutes++;
seconds = 0;
}
else if(minutes == 60) {
return "Out of time!";
}
}, 1000);
}
I've set a button in HTML to reset it, but when I use it to clear the timer, it continues running. This is the function with the clearInterval() in it.
function beginGame() {
cards = shuffle(cards);
for (var n = 0; n < cards.length; n++) {
allCards.innerHTML = "";
[].forEach.call(cards, function(item) {
allCards.appendChild(item);
});
cards[n].classList.remove("match", "open", "disable", "show");
}
//resetting values
moves = 0;
counter.innerHTML = moves;
star1.style.visibility = "visible";
star2.style.visibility = "visible";
star3.style.visibility = "visible";
lemon.style.visibility = "hidden";
seconds = 0;
minutes = 0;
clearInterval(interval);
var timer = document.querySelector("#timer");
timer.innerHTML = "0 Minute(s) 0 Seconds";
}
I've been researching this for a couple of days with no luck... could someone kindly help me understand how to stop the timer from continuing to run after reset is initialized? Thanks.
Because you have var interval inside beginTimer, the interval variable inside beginTimer will always reference the local variable, which is distinct from the outer interval (which is never touched). Once beginTimer ends, the local interval variable will simply be garbage collected. Leave off the var to assign to the outer variable instead:
var interval = null;
function beginTimer() {
interval = setInterval(function(){
var intervalinside the beginTimer() is error.
var seconds = 0, minutes = 0;
var timer = document.querySelector("#timer");
var interval = null;
function beginTimer() {
// var interval = setInterval(function(){
interval = setInterval(function(){
timer.innerHTML = minutes + " Minute(s) " + seconds + " Seconds";
seconds++;
if(seconds == 60) {
minutes++;
seconds = 0;
}
else if(minutes == 60) {
return "Out of time!";
}
}, 1000);
}
You need also to reset the ongoing timer before starting a new one. Please try the following:
var interval;
function beginTimer() {
clearInterval(interval);
interval = setInterval(function(){
...

i want to open a div after countdown timer stops

I am building an aptitude test with a timer. i want to show a div of time out on countdown finish. and is it possible to show a **Lean Modal Popup ** box on countdown finish. Please help!!!. Heres the code
Javascript
<script language="JavaScript" type="text/javascript">
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
window.onload = function () {
var display = document.querySelector('#time'),
timer = new CountDownTimer(5),
timeObj = CountDownTimer.parse(5);
format(timeObj.minutes, timeObj.seconds);
timer.onTick(format);
document.querySelector('button').addEventListener('click', function () {
timer.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
}
if(display.textContent == 0){
document.querySelector("#div1").style.display="block";
}
};
</script>
Html
<button>Start Count Down</button>
<div>Registration closes in <span id="time"></span> minutes!</div>
div to show
<div id="div1" style="display:none;" ><p>Hello</p></div>
Ok, so the thing is, you have this piece of javascript code:
window.onload = function () {
var display = document.querySelector('#time'),
timer = new CountDownTimer(5),
timeObj = CountDownTimer.parse(5);
format(timeObj.minutes, timeObj.seconds);
timer.onTick(format);
document.querySelector('button').addEventListener('click', function () {
timer.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
}
if(display.textContent == 0){
document.querySelector("#div1").style.display="block";
}
At the bottom, you have an "if" statement.
Just move that if statement into the "format" function as follow:
window.onload = function () {
var display = document.querySelector('#time'),
timer = new CountDownTimer(5),
timeObj = CountDownTimer.parse(5);
format(timeObj.minutes, timeObj.seconds);
timer.onTick(format);
document.querySelector('button').addEventListener('click', function () {
timer.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
console.log(display.textContent);
if(display.textContent == "00:00") {
document.querySelector("#div1").style.display="block";
}
}
};
Your code, the way it currently is, is not performing the check on every tick.
Also, you are not checking against "0". The value should be "00:00"
Of course, you can move the check to show the div into the tick event, but that is totally up to you.

Categories

Resources