jquery start multiple timers after each other - javascript

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>

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">

javascript dosen't read the value in html

So i want to make a program that start countingdown from a value that you choose but the issue is when i try to bring the value to javascript it dosen't work but when i type the value in html it work
here is my html code
<body>
<div id="count">
<input id="time" type="number" min="0">
<button id="button">Press here to begin the countdown</button>
</div>
<script src="lol.js"></script>
and here is my javascript code
var count = document.getElementById("count"),
seconds = document.getElementById("time").value ,
btn = document.getElementById("button"),
secondPass;
countDown = setInterval(function() {
secondPass()
} , 1000);
btn.onclick =
function secondPass(){
var minutes = Math.floor(seconds / 60),
remseconds = seconds % 60;
count.innerHTML = minutes + ":" + remseconds;
if (remseconds < 10){
remseconds = "0" + remseconds;
}
if (seconds> 0 ){
seconds = seconds - 1;
}
else {
clearInterval(countDown)
count.innerHTML = "done !"
}
}
The problem in your code was that you were trying to get the value before it was entered.
If I understood correctly, you wanted this:
var count = document.getElementById("count"),
btn = document.getElementById("button"),
secondPass;
btn.addEventListener("click", secondPass);
function secondPass() {
var seconds = document.getElementById("time").value
var countDown = setInterval(function () {
var minutes = Math.floor(seconds / 60),
remseconds = seconds % 60;
count.innerHTML = minutes + ":" + remseconds;
if (remseconds < 10) {
remseconds = "0" + remseconds;
}
if (seconds > 0) {
seconds = seconds - 1;
}
else {
clearInterval(countDown)
count.innerHTML = "done !"
}
}, 1000);
}
<div id="count">
<input id="time" type="number" min="0">
<button id="button">Press here to begin the countdown</button>
</div>
Main mistake - on time when you declare seconds variable - time input is empty.
I fixed your example, so you can figure out what was wrong
var count = document.getElementById("count"),
seconds,
btn = document.getElementById("button"),
countDown
btn.onclick = function() {
seconds = document.getElementById("time").value;
countDown = setInterval(function() {
secondPass()
}, 1000);
}
function secondPass(){
console.log('S', seconds)
var minutes = Math.floor(seconds / 60),
remseconds = seconds % 60;
count.innerHTML = minutes + ":" + remseconds;
if (remseconds < 10){
remseconds = "0" + remseconds;
}
if (seconds> 0 ){
seconds = seconds - 1;
}
else {
clearInterval(countDown)
count.innerHTML = "done !"
}
}

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 stop JavaScript Timer?

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.

how do i auto-submit the form when the timer comes to 00:00:00

I have used a countdown timer in my online examination website,the timer is shown via javaScript but problem is that after the 00:00:00 the timer shows negative time.I just want to stop the timer at 00:00:00 and submit a form when the time is over.below is the code that accurately displaying me the timer.
<?php
// Upon starting the section
session_start();
$_SESSION['TIMER'] = time() + 600; // Give the user Ten minutes
?>
<script type="text/javascript">
var TimeLimit = new Date('<?php echo date('r', $_SESSION['TIMER']) ?>');
</script>
<script type="text/javascript">
function countdownto() {
var date = Math.round((TimeLimit-new Date())/1000);
var hours = Math.floor(date/3600);
date = date - (hours*3600);
var mins = Math.floor(date/60);
date = date - (mins*60);
var secs = date;
if (hours<10) hours = '0'+hours;
if (mins<10) mins = '0'+mins;
if (secs<10) secs = '0'+secs;
document.body.innerHTML = hours+':'+mins+':'+secs;
setTimeout("countdownto()",1000);
if((hours==00)&&(mins==00)&&(secs==00))
document.alert("time is over");
}
countdownto();
</script>
I assume that your form has an ID attribute with this value yourForm.
// HTML
<form id="yourForm">[...]</form>
// JS
if((hours==00)&&(mins==00)&&(secs==00)) {
document.getElementById('yourForm').submit();
} else {
setTimeout(countdownto, 1000);
}
Note: Remove your setTimeout(countdownto, 1000); before the if statement
Alternative way.
You could kill the timeout with clearTimeout()
var myTimeout = setTimeout(countdownto, 1000);
if((hours==00)&&(mins==00)&&(secs==00)) {
clearTimeout(myTimeout);
document.getElementById('yourForm').submit();
}
clearTimeout documentation
Let's create a index.php file please check it. form submit on timer you can pass time through in javascript CountDown(5,div); function.
<html>
<body>
<form action="" method="post" name="mcQuestion" id="mcQuestion">
Name:<input type="test" name="name" value="Test">
<div><span id="display" style="color:#FF0000;font-size:15px"></span></div>
<div><span id="submitted" style="color:#FF0000;font-size:15px"></span></div>
</form>
<script>
var div = document.getElementById('display');
var submitted = document.getElementById('submitted');
function CountDown(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.innerHTML ="<b>" + minutes + "m : " + seconds + "s" + "</b>";
if (timer > 0) {
--timer;
}else{
clearInterval(interVal)
SubmitFunction();
}
},1000);
}
function SubmitFunction(){
submitted.innerHTML="Time is up!";
document.getElementById('mcQuestion').submit();
}
CountDown(5,div);
</script>
</body>
</html>

Categories