JavaScript clearInterval() does not clear the timer - javascript

I'm trying to set up a timer that will play a sound after a certain amount of minutes have passed. The number of minutes can be set in the input field time.
The problem is clearInterval function is not working.
When I set a timer to let's say 1 minute and afterward to 2 minutes, both timers are active.
How to remove the first-timer after changing the timer to 2 minutes only the new one will play a sound?
HTML:
<input id="time" />
<button onclick="timeFunction()">
set Timer
</button>
<p id ="timer"></p>
JS:
function timeFunction() {
var minuten = document.getElementById("time").value;
var sec = minuten * 60;
var msec = sec * 1000;
document.getElementById("timer").innerHTML = "Timer set to " + minuten + " minutes";
clearInterval(inter);
var inter = setInterval(function(){
document.getElementById('gong').play(); }
,msec);
}

var inter is a variable that only exists in your timeFunction. When the function finishes, inter does not exist anymore. When clearInterval runs, inter is undefined, because you haven't assigned it a value yet.
To fix it, declare the inter variable outside of your function. This will allow it to keep a value between multiple executions of timeFunction.
var inter;
function timeFunction() {
// other code
clearInterval(inter);
inter = setInterval(function(){
document.getElementById('gong').play();
}, msec);
}

Why don't you return the interval,
function timeFunction() {
var minuten = document.getElementById("time").value;
var sec = minuten * 60;
var msec = sec * 1000;
document.getElementById("timer").innerHTML = "Timer set to " + minuten + " minutes";
return setInterval(function(){
document.getElementById('gong').play(); }
,msec);
}
then you could go,
let intervals = timeFunction();
then you can clear it like so,
clearInterval(intervals);
this way you control how many times it iterates.

If you want this to run only once clear the interval after your work has been done. So your function can be re-written like this:
function timeFunction() {
var minuten = document.getElementById("time").value;
var sec = minuten * 60;
var msec = sec * 1000;
document.getElementById("timer").innerHTML = "Timer set to " + minuten + " minutes";
var inter = setInterval(function() {
document.getElementById('gong').play();
clearInterval(inter);
}, msec);
}
EDIT
You can also return inter variable from your function so you can use clearInterval whenever your script's logic needs the interval to stop.
function timeFunction() {
var minuten = document.getElementById("time").value;
var sec = minuten * 60;
var msec = sec * 1000;
document.getElementById("timer").innerHTML = "Timer set to " + minuten + " minutes";
var inter = setInterval(function() {
document.getElementById('gong').play();
}, msec);
return inter;
}
let intv = timeFunction();
// rest of your javascript
// ...
clearInterval(intv);

Related

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

Timer doesn't start running

I tried to make a normal Timer in Javascript and started coding something with help of some Tutorials.
I did it the same way as in the tutorial but my timer actually doesn't start running, and i don't know why.
Here is my Code:
var time = 0;
var running = 0;
function startPause() {
if(running == 0){
running = 1;
increment();
}
else{
running = 0;
}
}
function reset(){
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}
function increment() {
if(running == 1){
setTimeout(function(){
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}, 100);
}
}
</script>
i also made a fiddle you can check out here: https://jsfiddle.net/adamswebspace/5p1qgsz9/
what is wrong with my code?
I cleared a bit your code, and used setInterval instead of setTimeOut;
note that you have to use clearInterval in order to stop the timer
var time = 0;
var running = 0;
var timer = null;
function increment() {
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}
function startPause() {
if (running === 0) {
running = 1;
timer = setInterval(increment, 1000);
} else {
running = 0;
clearInterval(timer);
}
}
function reset() {
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}
you have to bind the function like the following
var vm = this;
vm.startPause = function startPause() {
if (running == 0) {
running = 1;
vm.increment();
} else {
running = 0;
}
}
https://jsfiddle.net/f7hmbox7/
In order for onclick to find the function in your code. It must be supplied in a <script> tag for JSFiddle.
You can just add
<script>
/** JS Here */
</script>
and it will work.
Keep in mind that all the errors coming from JS are showed in the console of your browser inspector.
https://jsfiddle.net/dzskncpw/

Javascript Second into Minutes:Seconds

I am working on a clock that needs to display seconds into a
minutes:seconds
format.
I have worked on some auxiliary functions for display, but I have never really gotten the full display. Here is some of my code:
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = time;
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
//Timer Display
var minutes = time/60;
var second = time%60;
var display = minutes + ":" + seconds;
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="stopTimer()">Stop</button>
Thie formatTime function below will take a number of seconds, and convert it to MM:SS format (including padded zeroes):
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = formatTime(time);
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
function formatTime(seconds) {
//Timer Display
var minutes = seconds / 60;
var second = seconds % 60;
return ('0'+minutes).substr(-2) +":"+ ('0'+seconds).substr(-2);
}
first of all you have to use clearInterval, then you don't update your display every second
check this fiddle out

Javascript Function activates before button is clicked

If requirements are met when you click the button it will display a count down timer. Problem is it displays the countdown timer BEFORE you even click the button. I'm not sure what I'm overlooking.
<input id="upgrade" type="button" value="Upgrade" onclick="timer();" />
<br><br><br><br>
<p id="countdown_timer"></p>
<script>
function display_timer(){
document.getElementById("countdown_timer").innerHTML = "<span id='countdown' class='timer'></span>";
}
</script>
<script>
var currently_upgrading = 0;
var current_ore = 398;
var current_crystal = 398;
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
if(currently_upgrading == 1){alert('You are already upgrading a module.');return;}
if(current_ore <= 299){alert('You need more ore.');return;}
if(current_crystal <= 299){alert('You need more crystal.');return;}
display_timer();
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
You need to move countdownTimer variable into your timer() function.
Try changing the last lines of timer() to be like this:
if (seconds == 0) {
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
setTimeout(timer, 1000);
}
and remove the setInterval line.
Speaking generally, setTimeout is much preferred to setInterval, because it doesn't require a managed state (countdownTimer in your example) and is far more flexible.
Also note that passing a string as in setTimeout('timer()', 1000) is obsolete, just pass a function: setTimeout(timer, ...).
This line
var countdownTimer = setInterval('timer()', 1000);
will execute 1 second after the page loads as well as on the button click and this calls the display_timer function.
you have called it in setInterval function, so it will starts immediately , because setInterval function runs after page loads and not on click and setInterval uses your function

How to create a toggle button in Jquery-mobile?

I want my button to change color if clicked but it seems not working in this JQuery-Mobile. and If its clicked it seems like it increases the time count speed i dont know why.
Any help please guys.
var seconds = 0;
var minutes = 0;
var timer = null;
function toggle(ths) {
var clicked = $(ths).val();
$(ths).toggleClass("btnColor");
$("#tb").toggleClass("btnColorR");
$("#lblType").html(clicked);
$("#setCount").html(" minutes : " + minutes + " seconds : " + seconds);
//duration time
seconds = seconds + 1;
if (seconds % 60 == 0) {
minutes += 1;
seconds = 0;
}
timer = timer = setTimeout("toggle()", 1000);
}
try :
timer=setTimeout(function(){
toogle();
},1000);

Categories