Why is my latest code overriding the rest of my code - javascript

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>

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

Pause and start JS countdown timer

I am trying to develop a centurion countdown timer for my website. It is a drinking game.
The way the timer works is: It is a 60 second countdown timer. Everytime the timer hits 0 it will +1 a shot counter and restart. It will do this 100 times.
The game is you must do 1 shot, every minute for 100 minutes. I am a beginner at JS and I am learning a lot, but I am seriously struggling to get this to work the way I want it to.
All I need is a "Start" Button, a "Pause" button and a "Reset" button but I can't seem to find a way to make these buttons work without messing the timer up.
Here is the HTML code:
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="timer()">
<input type="button" value="Pause" onclick="clearInterval(myTimer)">
</div>
and here is the JS code:
var seconds = 60;
var shots = 0;
var timer;
var c = 60;
function timer() {
timer = setInterval(myTimer, 1000)
}
function myTimer() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
If anyone could help me and show me what I am doing wrong and how I can make the code better, please do!
First, consider renaming either your method timer() or variable timer to disambiguate between the two.
Next, setInterval() returns an interval ID, which you store in timer.
clearInterval() takes the interval ID as the parameter, so try passing it the timer variable instead of myTimer (a function)
Little bit clean up needed. For clearInterval, u have to id of timer to clear
var seconds = 60;
var shots = 0;
var timer;
var c = 60;
function start() {
clearInterval(timer)
timer = setInterval(( ) =>{
updateUi()
}, 1000);
}
function pause() {
clearInterval(timer)
}
function updateUi() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="start()">
<input type="button" value="Pause" onclick="pause()">
</div>
You can also use Pub Sub model, to make code looks clean.
var seconds = 60;
var shots = 0;
var c = 60;
function Emitter() {
this.cb;
this.on = cb => {
this.cb = cb;
};
this.emit = () => {
this.cb && this.cb();
};
this.cancel = () => {
this.cb = null;
};
}
const emitter = new Emitter();
const tick = () => {
setInterval(() => {
emitter.emit();
}, 1000);
};
tick()
function start() {
emitter.on(updateUi);
}
function pause() {
emitter.cancel();
}
function updateUi() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="start()">
<input type="button" value="Pause" onclick="pause()">
</div>
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="minutes">100</p>
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="START" onclick="start()">
<input type="button" value="PAUSE" onclick="pause()">
<input type="button" value="RESET" onclick="reset()">
</div>
Changed the onclick functions to something more meaningful. Added an extra button and some more logic to auto-stop when hitting the 100 minutes.
var seconds = 60,
minutes = 100,
shots = 0;
timer = "";
// this will just stop the timer, if you click start it will resume from where it left off
function pause() {
clearInterval(timer);
}
// resets seconds/minutes/shots, stops game
function reset() {
clearInterval(timer);
seconds = 60;
minutes = 100;
shots = 0;
timer = "";
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML = c;
document.getElementById("shots").innerHTML = shots;
}
// starts game from wherever it was left
function start() {
timer = setInterval(function() {
document.getElementById("seconds").innerHTML = c--;
if (c === 0) {
document.getElementById("minutes").innerHTML = --minutes;
// when 100 minutes are up, game will stop and reset
if (minutes === 0) {
reset();
}
shots++;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}, 1000)
}

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>

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>

Categories