How to stop JavaScript Timer? - javascript

I have a simple Bootstrap page that includes a 45 second countdown timer and a button which I intend to include on a bigger project later. The countdown timer will start on a click of the button.
What I wanted to do is that when I click on the button again within the 45 seconds countdown interval, the counter will reset. I am not able to do that. What I tried to do is to use the clearInterval function at the very beginning of the errorTimer function. But, it did not work.
Here are my codes:
// Timer for error message - 45 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;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function errorTimer() {
var fortyFiveSeconds = 60 * .75,
display = document.querySelector('#time');
startTimer(fortyFiveSeconds, display);
};
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 mt-5"> </div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4 text-center">
<p id="time"></p>
</div>
<div class="col-md-4"></div>
</div>
</div>
<button type="button" class="btn btn-info" onclick="errorTimer()">Submit Button</button>

Use clearInterval like this
...
// Timer for error message - 45 seconds.
var timerId;
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
if(timerId != undefined) {
clearInterval(timerId)
}
timerId = 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);
}
function errorTimer () {
var fortyFiveSeconds = 60 * .75,
display = document.querySelector('#time');
startTimer(fortyFiveSeconds, display);
};
...

As #Shidersz mentioned, you need to store the id associated with the interval and use that id to clear the interval before resetting the clock.
// Timer for error message - 45 seconds.
var id = null;
function startTimer(duration, display) {
if (id !== null) {
clearInterval(id);
id = null;
}
var timer = duration,
minutes, seconds;
id = 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);
}
function errorTimer() {
var fortyFiveSeconds = 60 * .75,
display = document.querySelector('#time');
startTimer(fortyFiveSeconds, display);
};
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 mt-5"> </div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4 text-center">
<p id="time"></p>
</div>
<div class="col-md-4"></div>
</div>
</div>
<button type="button" class="btn btn-info" onclick="errorTimer()">Submit Button</button>

You could stop the timer by clearing the interval:
// Timer for error message - 45 seconds.
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var interval = 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);
return function(){ clearInterval(interval); };
}
function errorTimer () {
var fortyFiveSeconds = 60 * .75,
var display = document.querySelector('#time');
var stopper = startTimer(fortyFiveSeconds, display);
setTimeout(stopper, 20 * 1000); // stop timer 20 seconds later.
};
I make use of a simple function returned by the startTimer function, that can be used to clear the interval at a later point.

Related

Submit the value of a timer which is then use for JS function

I am trying to enable the user to set the value of a timer and then to see the countdown timer displayed on the webpage.
Here is my HTML code:
<p>Timer:</p>
<input type="text" name="timing" id="demoC" style="height:50px;" value="3">
<div id="answer">Your dish will be ready in <span id="time"></span> minutes!</div>
<input type="submit" name="submit" class="submit" value="Submit">
And here is my JS 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.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
jQuery(function ($) {
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
});
This code is working because in the HTML file, I hardcoded the value to 3 minutes directly.
But I would like to remove this value="3"and be able to set it up manually in the input field.
But when I am doing that, the timer is not displayed.
First, you should add the 'id'-attribute to the input element:
<input type="submit" name="submit" class="submit" value="Submit" id="submit">
But just setting the function glitches out the timer if the user inputs multiple values, so you should change your code like this:
var clearIntervalId;
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
clearIntervalId = 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.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
$("#submit").click(function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
if (typeof clearIntervalId !== 'undefined') {
clearInterval(clearIntervalId)
}
startTimer(myVar, display);
});
clearIntervalId is used, so that the previous running setInterval()-function is getting cleared out everytime the user clicks the button, so that there won't be interfering changes in the current minutes + seconds.
What do you need is a trigger for the startTimer function after event
and in your code the event is a button click
Add id attribute to your button
<input type="submit" id="submit" name="submit" class="submit" value="Submit">
and add click event listener to your button
$("#submit").on("click",function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
})
jQuery(function ($) {
$("#submit").on("click",function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
})
});
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.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Timer:</p>
<input type="text" name="timing" id="demoC" style="height:50px;" value="3">
<div id="answer">Your dish will be ready in <span id="time"></span> minutes!</div>
<input type="submit" id="submit" name="submit" class="submit" value="Submit">

Why is my latest code overriding the rest of my code

I have a page with timers. the code for my latest timer only functions properly. but the rest of the timers don't such as the 10 minute timer. It only shows you the set time for the timer. Is my latest code overriding my other code? Are variables being mixed between the two timers? I'm planning on adding several timers to the page, but I got stuck when this happened.
Link to code: http://jsfiddle.net/vtoLx02j/2/
<body>
<div id="1Div">
<h4>Question goes here?</h4>
<input type="text"id="name1"/>
<button onclick="myFunction1()" id="button0" class="button3">Enter</button>
</div>
<div id="2Div" style="display:none;">
<h4 id=typeE>How much time do you think you need in minutes?</h4>
<button onclick="myFunction2()" id="button1" class="button3">10 minutes</button>
<button onclick="myFunction3()" id="button2" class="button3">20 minutes</button>
</div>
<script>
function myFunction1(){
document.getElementById("1Div").style.display="none";
document.getElementById("2Div").style.display="block";
}
</script>
<script>
function myFunction2(){
document.getElementById("2Div").style.display="none";
document.getElementById("timer10").style.display="block";
}
</script>
<script>
function myFunction3(){
document.getElementById("2Div").style.display="none";
document.getElementById("timer20").style.display="block";
}
</script>
<div id="timer10" style="display:none">
<script>
function startTimer10(duration10, display10) {
var timer10 = duration10, minutes10, seconds10;
setInterval(function () {
minutes10 = parseInt(timer10 / 60, 10);
seconds10 = parseInt(timer10 % 60, 10);
minutes10 = minutes10 < 10 ? "0" + minutes10 : minutes10;
seconds10 = seconds10 < 10 ? "0" + seconds10 : seconds10;
display10.textContent = minutes10 + ":" + seconds10;
if (--timer10 < 0) {
timer10 = duration10;
}
}, 1000);
}
window.onload = function () {
var tenMinutes = 60 * 10,
display10 = document.querySelector('#time10');
startTimer10(tenMinutes, display10);
};
</script>
<body>
<center><div><span id="time10">10:00</span></div></center>
</body>
</div>
<div id="timer20" style="display:none">
<script>
function startTimer20(duration20, display20) {
var timer20 = duration20, minutes20, seconds20;
setInterval(function () {
minutes20 = parseInt(timer20 / 60, 10);
seconds20 = parseInt(timer20 % 60, 10);
minutes20 = minutes20 < 10 ? "0" + minutes20 : minutes20;
seconds20 = seconds20 < 10 ? "0" + seconds20 : seconds20;
display20.textContent = minutes20 + ":" + seconds20;
if (--timer20 < 0) {
timer20 = duration20;
}
}, 1000);
}
window.onload = function () {
var twentyMinutes = 60 * 20,
display20 = document.querySelector('#time20');
startTimer20(twentyMinutes, display20);
};
</script>
<body>
<center><div><span id="time20">20:00</span></div></center>
</body>
</div>
</body>
You can simply combine all your functions into single startTimer() function.
I am not sure why you are repeating your code again and again to achieve the same results. Its good to have less code but have the same results.
So here's is what i have done and simplified your code.
I have combined both timers into one function
You do not need to use display none and block again on show time duration
When you click on the timer just pass the minutes to the timer function and the span will start displaying the time remaining
You do no need two span to display timer separately you can do all that in one span
You were using script tag so many times which are unnecessary
Both timers are working perfectly with less code and same results.
You can have multiple timers now you just need to pass the minutes to your startTimer() function and timer will start from the given time.
Live Demo
//Start 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);
}
//1
function myFunction1() {
document.getElementById("1Div").style.display = "none";
document.getElementById("2Div").style.display = "block";
}
//10 Minutes
function myFunction2() {
document.getElementById("2Div").style.display = "none";
var tenMinutes = 60 * 10,
display10 = document.querySelector('#timerDuration');
startTimer(tenMinutes, display10);
}
//20 minutes
function myFunction3() {
document.getElementById("2Div").style.display = "none";
var twentyMinutes = 60 * 20,
display20 = document.querySelector('#timerDuration');
startTimer(twentyMinutes, display20);
}
<body>
<div id="1Div">
<h4>Question goes here?</h4>
<input type="text" id="name1" />
<button onclick="myFunction1()" id="button0" class="button3">Enter</button>
</div>
<div id="2Div" style="display:none;">
<h4 id=typeE>How much time do you think you need in minutes?</h4>
<button onclick="myFunction2()" id="button1" class="button3">10 minutes</button>
<button onclick="myFunction3()" id="button2" class="button3">20 minutes</button>
</div>
<center>
<div><span id="timerDuration"></span></div>
</center>
</body>

How to add timer to bootstrap progress bar in javascript

I have a timer with the progress bar. the timer works fine. but I want to move the progress bar with the timer. I'm using the bootstrap progress bar. if I remove the bar variable from the function the timer works fine but with the progress, it stops working. any suggestions? thank you :)
function startTimer(duration, display, bar) {
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;
bar.css('width', minutes + '%');
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var minutes = 60 * 15,
display = document.querySelector('#time');
bar = document.querySelector('#progressBar');
startTimer(minutes, display, bar);
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<div class="progress mx-auto mb-2" style="max-width: 300px;">
<div class="progress-bar bg-success" role="progressbar" id="progressBar" style="width: 100%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<span id="time">15:00</span>
Use bar.style.width, .css() is a jQuery function.
For correct percentage, calculate total and remaining seconds and set bar width based on that
function startTimer(duration, display, bar) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
var totalSeconds = 15 * 60
, remainingSeconds = minutes * 60 + seconds
bar.style.width = (remainingSeconds*100/totalSeconds) + "%";
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 minutes = 60 * 15,
display = document.querySelector('#time');
bar = document.querySelector('#progressBar');
startTimer(minutes, display, bar);
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<div class="progress mx-auto mb-2" style="max-width: 300px;">
<div class="progress-bar bg-success" role="progressbar" id="progressBar" style="width: 100%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<span id="time">15:00</span>

jquery start multiple timers after each other

I have this code
var duration = 60 * $(".duration").val(),
display = $(".timer");
startTimer(duration, display);
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.html(minutes + ":" + seconds);
if (--timer < 0) {
display.html("DONE!");
}
}, 1000);
}
I have + button to let the user add multiple timers like this
<input type="text" class="duration" /> //Desired duration for first timer
<div class="timer"></div>
<input type="text" class="duration" /> //Desired duration for second timer
<div class="timer"></div>
<input type="text" class="duration" /> //Desired duration for third timer
<div class="timer"></div>
after that I want the user to click a button to start the timers but one at a time after the first timer finished the second one starts and etc
Thank you
Here's the first way that came to mind that didn't involve much change to your existing startTimer() function - basically I just added a callback argument, and then another function to start the next timer. (This code could be tidied up quite a bit, but it should give you some ideas...)
$("button").click(function() {
var durations = $(".duration");
var current = -1;
durations.prop("disabled", true);
$(this).prop("disabled", true);
function startNext() {
if (++current < durations.length)
startTimer(durations.eq(current).val() * 60,
durations.eq(current).next(),
startNext);
else {
durations.prop("disabled", false);
$("button").prop("disabled", false);
}
}
startNext();
function startTimer(duration, display, callback) {
var timer = duration,
minutes, seconds;
var intId = 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.html(minutes + ":" + seconds);
if (--timer < 0) {
display.html("DONE!");
clearInterval(intId);
callback();
}
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
First:
<input type="text" class="duration" value="0.05" />
<div class="timer"></div>
Second:
<input type="text" class="duration" value="0.05" />
<div class="timer"></div>
Third:
<input type="text" class="duration" value="0.1" />
<div class="timer"></div>
<button>Start</button>

how can activate my countdown timer with button?

I have a countdown timer function writed in javascript.Its working but it starts when i start the page.I want it should be start when the button clicked.
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.text(minutes + ":" + seconds);
if (--timer < 0) {
// timer = 0;
time.style.display = "none";
time2.style.display2 = "none";
redxsms.style.display = "none";
onaysms.style.display = "none";
tekraruyarionay.style.display = "block";
tekraruyarired.style.display = "block";
// time.style.display="block";
setTimeout(function () { location.reload() }, 5000);
}
}, 1000);
}
jQuery(function ($) {
var fiveMinutes = 60 * 3,
display = $('#time');
display2 = $('#time2');
startTimer(fiveMinutes, display);
startTimer(fiveMinutes, display2);
});
this is the countdown function.
<button class="ui toggle button" onclick=" hideshow(document.getElementById('onaysms')); show(this);" id="onaytoggle">
this is button when i click it should activate.
<span id="time"></span>
It starts when the page start how can i start when the button clicked?
Insert your timer call in an "onclick" event like this, it will be fired when you click on the button.
If you have several buttons on your page, i would advise you to give one an id by adding this in your html : id='timerToggle' and then replacing the $("button.toggle") in the code below by $("#timerToggle")
jQuery(function ($) {
$("button.toggle").click(function(){
var fiveMinutes = 60 * 3,
display = $('#time');
display2 = $('#time2');
startTimer(fiveMinutes, display);
startTimer(fiveMinutes, display2);
});
});

Categories