I'm trying to countdown 60 seconds once I click the begin button and at 0 I don't want to just hide the counter, I want it to be reset. I ran into 2 problems:
When I click the begin button again it's not starting over.
The begin button is not disabled once I click it to start the countdown.
While its counting down, when I press the begin button it accelerate the countdown.
Any help is appreciated, here is the code:
function begin() {
$('#begin').prop('disabled');
myTimer = setInterval(function() {
$('#timing').html(timing);
if (timing === 0) {
alert('Too late! Try again');
clearInterval(myTimer);
$('#timing').hide();
}
timing--;
}, 1000);
}
You have several issues:
You need .prop("disabled", true) to disable the button.
You need to reset the timing variable when you restart the timer.
You need to enable the button when the timer finishes so it can be pressed again.
You need to display the initial count when you start the timer
Code:
var timing;
var myTimer;
function begin() {
timing = 60;
$('#timing').html(timing);
$('#begin').prop('disabled', true);
myTimer = setInterval(function() {
--timing;
$('#timing').html(timing);
if (timing === 0) {
alert('Too late! Try again');
clearInterval(myTimer);
$('#begin').prop('disabled', false);
}
}, 1000);
}
Working demo (with a shorter interval time so it counts down faster): http://jsfiddle.net/jfriend00/xxs7t0gd/
Related
I can't for the life of my figure out how to get this to work bug free.
The button in the code below needs to do three things.
Start a countdown when clicked (works)
End the countdown automatically, and reset itself when it reaches 0(works)
Reset itself prematurely if its clicked in the middle of a countdown(works, sort of)
Bug: when clicked repeatedly it starts multiple countdowns, and more or less breaks. It needs to either reset itself or start a countdown if clicked repeatedly. There should never be more than one countdown.
It works fines as long as people press the button, wait a second, and then press it again to stop it.
The bug I'm running into is if someone spam clicks it, it starts multiple countdowns and generally just breaks the button. I've tried a lot of different methods to fix it, and this is the closest I've gotten.
var i = 29;
let running=false;
$("#startButton").click(function () {
if(running==false){
var countdown = setInterval(function () {
$("#startButton").text("Reset Timer");
running=true;
$("#stopWatch").html(i);
i--;
if (i <0)
{
$("#startButton").text("Start Timer");
running=false;
clearInterval(countdown);
i = 29;
$("#stopWatch").html(i);
}
$("#startButton").click(function () {
$("#startButton").text("Start Timer");
running=false;
clearInterval(countdown);
i = 29;
$("#stopWatch").html(i+1);
});
}, 1000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stopWatch">30</div>
<button id="startButton">Start Timer</button>
Welcome to Stack Overflow #William!
I'm not sure what this means: Reset itself prematurely if its clicked in the middle of a countdown(works, sort of). But I managed to fix your bug on spamming button click and for item 3, i just do reset the countdown from initial state. See snippets below:
// Get attribute value from div `stopwatch`. This is for resetting from default value.
var initial = $('#stopWatch').attr("value");
// Assigned initial value to var i.
var i = initial;
$("#stopWatch").html(i);
let running = false;
// Created a separate function to call from button click.
function run(timer = true) {
if (timer) {
running = true;
$("#startButton").text("Reset Timer");
$("#stopWatch").html(i);
var countdown = setInterval(function () {
i--;
$("#stopWatch").html(i);
if (i <= 0) {
running = false;
$("#startButton").text("Start Timer");
clearInterval(countdown);
i = initial;
$("#stopWatch").html(i);
}
}, 1000);
} else {
running = false;
clearInterval(countdown);
i = 0;
$("#startButton").text("Start Timer");
}
}
$("#startButton").click(function () {
// Check if its not running and var i is not 0
if(!running && i != 0) {
run();
// Check if its running and var i is not 0 to ensure that if someone spam the button it just reset the countdown.
} else if (running && i != 0) {
// Will return the else{} on function run().
run(false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stopWatch" value="30"></div>
<button id="startButton">Start Timer</button>
Added some comments on the snippet. Feel free to ask if you have any questions.
I am using this function to auto-click a button after 15 seconds. The problem is the user doesn't leave the page after the option is run and it may be re-run again on the same page but the timer continues. In fact, the timer continues even if I do the action myself.
<script type="text/javascript">
time = 15;
interval = setInterval(function() {
time--;
document.getElementById('Label1').innerHTML = "You must choose in " + time + " seconds"
if (time == 0) {
// stop timer
clearInterval(interval);
// click
document.getElementById('thebutton').click();
}
}, 1000)
</script>
So this script should run the timer and "press" the "thebutton" in fifteen seconds and then the timer should stop counting and reset until run again. If the button is pressed manually before 15 seconds it should still reset.
<input type='submit' id='thebutton' value='Done'></input>
Hopefully this is clear. I am still new and learning.
Set a base time and then reset it to that.
<script type="text/javascript">
time = 15;
baseTime = 15;
interval = setInterval(function() {
time--;
document.getElementById('Label1').innerHTML = "You must choose in " + time + " seconds"
if (time == 0) {
// stop timer
clearInterval(interval);
// click
document.getElementById('thebutton').click();
time = baseTime;
return false;
}
}, 1000)
</script>
I had a look at the code and the most critical thing that I think you should look at is that the button has no "onclick" function.
This means that clicking the button does nothing because you have not put a function there that does something when you click it.
I wrote some code that I hope helps:
let time = 15;
const label = document.getElementById("Label1");
const button = document.getElementById("thebutton");
const getText = () => `You must choose in ${time} seconds`;
const interval = setInterval(() => {
time--;
label.innerHTML = getText();
if (time === 0) {
// stop timer
clearInterval(interval);
// click
button.click();
}
}, 1000);
const stopTime = () => {
clearInterval(interval);
time = 15;
label.innerHTML = getText();
};
And in your html something like this:
<input type='submit' id='thebutton' value='Done' onclick="stopTime()" />
Finally I made a small video where I walk through the code, it could be useful as well: https://youtu.be/ZYS9AcxO3d4
Have a great day!
If you only want the button to be clicked once after 15 seconds then you should use the setTimeout() function instead of setInterval().
Then if you do not want the auto-click to happen if the user clicks the button then you would need to add an onClick handler to your button that calls clearTimeout().
I assume you want the label updated as the seconds count down? And it's unclear how the timer is started. Check the below code and see if it does what you expect.
var time, interval;
function stopTimer() {
if (interval) {
clearInterval(interval);
interval = null;
}
time = 15;
}
function timerAction() {
$('#lblStatus').text("You must choose in " + time + " seconds");
if (time-- <= 0) {
stopTimer();
console.log("done!");
$("#btnStop").click();
}
}
function startTimer() {
stopTimer();
timerAction();
interval = setInterval(timerAction, 1000);
}
$("#btnStart").click(function() {
startTimer();
});
$("#btnStop").click(function() {
stopTimer();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id=lblStatus></span>
<button id='btnStart'>Reset / Start</button>
<button id='btnStop'>Stop</button>
If you want to run only once, you can use setTimeout function
setTimeout(your code, 15000);
I really need some help with my Javascript countdown timer.
I am trying to make a countdown timer, for a quiz game, that resets and starts over when a button is pressed.
I can get it to reset and start over but if I press the button before time gets to 0, it will count down super fast.
Can anyone help? Here's the code:
<script type="text/javascript">
var countdown;
var time;
function init() {
time = 11;
reset();
trigger();
}
function trigger() {
if(time > 0) {
time--;
document.getElementById('timer').innerHTML = time;
if(time > 0) {
countdown = setTimeout('trigger()', 1000);
}
}
}
function reset() {
clearTimeout(trigger);
}
</script>
<input type="button" value="Reset" onclick="init()" />
<h3 id="timer">10</h3>
Of course I have the basic HTML document set up. The script is inside the tags and there's no difference in timer behavior if I place the script in element.
Thank you in advance!
You're not clearing the timeout in the reset. it should be
clearTimeout(countdown);
like this fiddle
I have a setinterval that moves bulldozer from the right to the left.
In the jsfiddle below, the setInterval must stop itself after 5 seconds. (used a settimeout and clearinterval for that) but it's not working. Can anyone help me?
http://jsfiddle.net/B5MKj/11/
var gameover;
gameover = setInterval(function () {
setTimeout(function () {
clearInterval(movingbulldozer);
}, 55000);
}, 10);
You had a typo in your fiddle, updated fiddle, if works just fine, but instead of 5000 ms you had 55000ms set for the timeout.
setTimeout(function () {
clearInterval(movingbulldozer);
}, 5000);
In your example, movingbulldozer is undefined. If you're trying to clear the interval, clear the interval with the right reference. In your example, this would be clearInterval(gameover);
The problem with your example is that every 10 ms you're adding a timeout to the DOM which clears the interval.
var timeout, interval, date,
i = 0;
$(document).ready(function() {
interval = setInterval(function() {
date = new Date();
i++;
$('#debug').html('Interval parsed at '+date.getTime()+', interval #'+i);
if (i >= 100) { // According to your example
$('#debug').html('Starting timeout...');
timeout = setTimeout(function() {
$('#debug').html('Timed out');
}, 5000);
clearInterval(interval);
}
}, 10);
});
Check out my example, see if it helps. :)
http://jsfiddle.net/faqq5/
how would you guys reinitiate a javascript timer after it's been stopped. Basically I need the timer to stop, and then start again on rollout of a div. I have
var timer = setInterval(myFunction, 1000);
timer
function myFunction(){<br/>
if(){
do this
}
else if () {
do this
}
};
then I have
$("td").hover(
function () {
window.clearInterval()
},<br/>
function () {
timer
}
);
all works good except it doesn't start again on hover off. If I put a new timer in hover off the timer starts to speed up every time you hover on and off.... Any ideas.
Thanks
var intervalID = setInterval(myFunction, 1000);
function myFunction(){
//logic goes here
};
$("td").hover( function () {
window.clearInterval(intervalID)
},
function () {
intervalID = setInterval(myFunction, 1000);
} );
Explanation: What's happening is that the setInterval is returning the ID associated with that interval.
I did a littse jsFiddle to show it works.
NOTE: this doesn't pause the current Interval. It stops it and starts it again. So if you were in a 10sec interval at 9 secs and stopped it. When it starts again it will take another 10secs.