Reset 'setIntervall' counter / remove existing instances - javascript

A timer will count down from 10 minutes on loading the page. If I do a mousedown after some time, the countdown should start again.
But then the timer will jump between both values. It seems, that both are counting. How can I remove exiting intervals?
Template.content.onRendered(function() {
var display = document.querySelector('#timer');
startTimer( 600, display);
});
Template.content.events({
'mousedown': function() {
var display = document.querySelector('#timer');
startTimer( 600, display);
// this will start a new counter
// but I want the old one to be replaced
}
});
startTimer = function(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
}
timer();
setInterval(timer, 1000);
};

Add a new variable in your js
var timer = 0;
Update your code in startTimer function from
setInterval(timer, 1000);
to
timer = setInterval(timer, 1000);
And then in your mousedown event handler function, add following line
clearInterval(timer);

Related

How to make this countdown repeat after the time runs out?

I'm very new to Javascript and I found myself stuck with this issue. I want to make this countdown repeat after the time runs out, however I'm not really sure how to do it, and my attempts to make it work failed. Would appreciate help how to do it, Thanks.
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;
if (--timer < 0) {
// here's the problem. not sure how to make it repeat
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
Tried using clearInterval() and setTimeout() but instead of it working the countdown either went past 00:00 (00:0-1 and so on) or just didn't work at all.
You can reset timer:
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;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
What you're describing is a forever countdown.
Note that eventhough you specify 1000 in the setInterval(). The timer isn't precise, so the callback may fire less than or greater than 1000ms. It is much safer to capture the startTime and then calculate the currentTime when the callback fires and measure the elapsedTime. This will give a true indication of elapsed time regardless of whether the timer is running slow or fast.
Because of the reset requirement. I actually infer that the timer is an infinite loop. We run it forever. There is no description as to when the timer is aborted, so, we just continue measuring currentTime and note elapse.
I use elapsedTime = (currentTime - startTime) / 1000 to calculate the elapsed time in seconds. Then, I elapsed % duration to make the counter stop at the duration and reset. Finally, I flip the math countdown = duration - 1 - (elapsedTime % duration) so instead of counting up, it counts down.
We then break down countdown into the minutes and seconds components.
Below is a fully working example that uses jQuery.
function startTimer(duration, display) {
let startTime = Date.now();
setInterval(function() {
let currentTime = Date.now();
let elapsedTime = Math.floor((currentTime - startTime) / 1000);
let countdown = duration - 1 - (elapsedTime % duration);
let minutes = Math.floor(countdown / 60).toString().padStart(2, "0");
let seconds = (countdown % 60).toString().padStart(2, "0");
display.text(minutes + ":" + seconds);
}, 1000 );
}
let fiveMinutes = 60 * 5;
let display = $("#time");
startTimer(fiveMinutes, display);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="time">mm:ss</label>

How do you escape out of an alert box and resume flow of action? - Javascript

So i am writing a simple javascript timer, and at 30 seconds it prompts the user with an alert box if they would like to reset the count down or let it continue.
I am able to reset the timer however I get stuck when the user clicks cancel on the alert box.
I tried letting the timer just resume at its current time but that doesn't help as the alert box just keeps reappearing
I am still very new to javascript so I would like to stay using vanilla js till I get a deeper understanding of the fundamentals!
Any guidance would be greatly appreciated!
Heres my code:
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;
if(timer<30){
var message = confirm("Would you like to extend timer?");
if (message == true) {
timer = 60 * 1;
}
else{
timer = timer;
}
}
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function resetTimer() {
timer = 60 * 1;
}
window.onload = function () {
var fiveMinutes = 60 * 1,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
just put if(timer==30) instead of if(timer<30) so that exactly at count of 30 units of time, you get asked once for confirmation at that instance (However be aware that until the confirmation is done, prompts will keep popping up every second). if you extend it, it will again wait till your timer goes down to 30 unit, else it will simply go down to 0 and break out.
function startTimer(duration, display) {
var timer = duration,
minutes,
seconds;
function timerFunc() {
timer -= 1;
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;
if (timer == 30) {
var message = confirm("Would you like to extend timer?");
if (message == true) {
timer = 60;
} else return alert("Your timer has been stopped.")
}
setTimeout(timerFunc, 1000);
}
timerFunc();
}

Countdown Timer not Stopping with clearInterval()

I'm having a problem get this countdown timer to stop at zero so the time won't show as a negative value. The console.log is getting called and works fine but for some reason the clearInterval() is not. This is driving me crazy and I'm close to quitting.
const timerContainer = document.getElementById('timerContainer');
const THREEMINUTES = 60 * 0.1;//5 seconds for testing
startTimer(THREEMINUTES, timerContainer);
function startTimer(duration, display) {
let start = Date.now();
let diff, min, sec;
let timer = () => {
diff = duration - (((Date.now() - start) / 1000) | 0);
//use bitwise to truncate the float
min = (diff / 60) | 0;
sec = (diff % 60) | 0;
min = min < 10 ? '0' + min : min;
sec = sec < 10 ? '0' + sec : sec;
display.textContent = min + ':' + sec;
if (diff <= 0) {
stopTimer();
submit.disabled = 'true';
};
};
//call timer immediately otherwise we wait a full second
timer();
setInterval(timer, 1000);
function stopTimer() {
clearInterval(timer);
console.log("time's up", diff);
};
}
<div id="timerContainer"></div>
You are not saving the result of setInterval(timer, 1000);
you should use this:
let timerId;
timer();
timerId = setInterval(timer, 1000);
function stopTimer() {
clearInterval(timerId);
console.log("time's up", diff)
};
As you might see, the result of setInterval is a number (object in node), and all you then need to do is pass that value to clearInterval thus we save the value in the variable timerId for reference.
Don't pass the function that you want stopped to clearInterval().
Pass a reference to the timer that you started, so you need to make sure that when you start a timer, you capture a reference to the ID that will be returned from it.
// Function that the timer will invoke
function callback(){
. . .
}
// Set up and initiate a timer and capture a reference to its unique ID
var timerID = setInterval(callback, 1000);
// When needed, cancel the timer by passing the reference to it
clearInterval(timerID);
The code is fixed make sure you fix your submit button code.
You should first assign the value of setInterval to a variable. That variable is used while calling clearInterval which infact clears the interval.
const timerContainer = document.getElementById('timerContainer');
const THREEMINUTES = 60 * 0.1;//5 seconds for testing
startTimer(THREEMINUTES, timerContainer);
var timer = null;
function startTimer(duration, display) {
let start = Date.now();
let diff, min, sec;
let timer = () => {
diff = duration - (((Date.now() - start) / 1000) | 0);
//use bitwise to truncate the float
min = (diff / 60) | 0;
sec = (diff % 60) | 0;
min = min < 10 ? '0' + min : min;
sec = sec < 10 ? '0' + sec : sec;
display.textContent = min + ':' + sec;
if (diff <= 0) {
stopTimer();
submit.disabled = 'true';
};
};
//call timer immediately otherwise we wait a full second
timer();
timer = setInterval(timer, 1000);
function stopTimer() {
clearInterval(timer);
console.log("time's up", diff);
};
}

How can I make a timer subtract five minutes when a buton is pressed?

I'm making a riddle where people have 45 minutes to find the solution, but I want the timer to go down five minutes when they answer incorrectly to prevent them from just guessing the answer. This is what I have for the timer:
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
var cat1 = $("input[#name=Verdachte]:checked");
if (cat1.val() != "2") {
cat1.val("you are right :)");
cat1.attr("disabled", true);
start -= 1000 * 60 * 5;
}
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function() {
var fortyfiveMinutes = 60 * 45,
display = document.querySelector('#time');
startTimer(fortyfiveMinutes, display);
}
But it just keeps subtracting five minutes all the time, so I made a send button for it:
$("#results").click(function() {
if (cat1.val() === "2") {
cat1.val("you are right :)");
cat1.attr("disabled", true);
start -= 1000 * 60 * 5;
}
};
But now the timer just disappears completely, how can I fix this?
try this , I create a new function to check value and set varaibles as globals to access easy ,and change value of 'start' if value of textbox is wrong
var start = Date.now();
function startTimer(duration, display) {
var diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function() {
var fortyfiveMinutes = 60 * 45,
display = document.querySelector('#time');
startTimer(fortyfiveMinutes, display);
}
function checkValue() {
var cat1 = $("#Verdachte");
if (cat1.val() == "2" || cat1.attr("disabled")) {
cat1.val("you are right :)");
cat1.attr("disabled", true);
} else {
cat1.val("Wrong :(");
start -= 1000 * 60 * 5;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>
<input id="Verdachte">
<button onclick="checkValue()"> click me</button>

countdown timer with number reduction after set point?

I've got a working countdown timer which starts at 30 minutes.
With only 3 minutes left (so after 27 minutes) I'd like the number 250 to decrease at random intervals from 3 minutes left down to the end of the countdown.
Any ideas?
https://codepen.io/anon/pen/bWoGrb
// Stopwatch
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;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var thirtyMinutes = 60 * 30,
display = document.querySelector('#stopwatch');
startTimer(thirtyMinutes, display);
};
<div id='stopwatch'></div>
Maybe use something like this (I hope I clearly understood the question):
Just using a if/else within the condition something to say: Go normal when more than 60*3, and when under 60*3 seconds rest, there is chance to do nothing
// Stopwatch
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
if(timer > 60*3 || Math.random() < 0.25) {
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;
if (--timer < 0) {
timer = duration;
}
} else {
/* do not reduce the timer to wait 1 interval more */
/* or maybe do like `timer -= Math.random()` if you want to reduce it faster */
}
}, 1000);
}
window.onload = function () {
var thirtyMinutes = 60 * /*30*/ 4, // just set to 4 to see faster
display = document.querySelector('#stopwatch');
startTimer(thirtyMinutes, display);
};
<div id='stopwatch'></div>

Categories

Resources