I currently have a timer , that counts down from 2 minutes.
what I would like to happen is when the button is clicked, it is hidden until the timer runs out and when the timer runs out it is visible/clickable again. I would also like the timer to be hidden until the button is clicked, to be visible when the button is clicked and then to be hidden once the timer runs out.
here is my code
js
function startTimer() {
userInput = 120;
if(userInput.length == 0){
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
function display( notifier, str ) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond( x ) {
return Math.floor(x/60) + ":" + x%60;
}
function setTimer( remain, actions ) {
(function countdown() {
display("countdown", toMinuteAndSecond(remain));
actions[remain] && actions[remain]();
(remain -= 1) >= 0 && setTimeout(countdown, 1000);
})();
}
setTimer(userInput, {
0: function () { alert( "Time Is Up. Please Sumbit Vote."); }
});
}
}
html
<div id="countdown"></div>
<input type="button" onclick="startTimer()" value="Start Timer">
fiddle
http://jsfiddle.net/grahamwalsh/qur9r3d8/
You can hide and unhide the button using JS
JSFiddle
Add an ID to your button
<input id="btn" type="button" onclick="startTimer()" value="Start Timer"/>
JScode
function startTimer() {
//hide button
document.getElementById("btn").style.display = "none";
//un-hide timer
document.getElementById("countdown").style.display = "inline";
userInput = 10;
if (userInput.length == 0) {
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
function display(notifier, str) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond(x) {
return Math.floor(x / 60) + ":" + x % 60;
}
function setTimer(remain, actions) {
(function countdown() {
display("countdown", toMinuteAndSecond(remain));
actions[remain] && actions[remain]();
(remain -= 1) >= 0 && setTimeout(countdown, 1000);
})();
}
setTimer(userInput, {
0: function () {
alert("Time Is Up. Please Sumbit Vote.");
//un-hide button
document.getElementById("btn").style.display = "inline";
//hide timer
document.getElementById("countdown").style.display = "none";
}
});
}
}
Here is a fiddle with the solution:
Use the display property:
document.getElementById("button1").style.display="none";
and to show:
document.getElementById("button1").style.display="block";
fiddle
Make sure to add button1 as an id to your button:
<input id="button1" type="button" onclick="startTimer()"
The fiddle shows where you should put this code...
I went ahead and built it from scratch using JQuery as your friend suggested. I think all the answers here using your setTimeout are taking the wrong approach. This is more of a job for setInterval which will provide slightly less performance overhead and much cleaner code.
Working Example: http://codepen.io/Chevex/pen/RNomGG
First, some simple HTML to work with.
<div id="timerDisplay"></div>
<button id="startTimer">Start Timer</button>
Next, a simple timer script.
// Passing a function to $() is the same as $(document).on('ready', function () { ... });
// It waits for the entire page to be loaded before running the function, which is usually what you want.
$(function () {
// Get reference to our HTML elements and store them as variables.
// I prepend them with dollar signs to signify they represent HTML elements.
var $startTimer = $('#startTimer');
var $timerDisplay = $('#timerDisplay');
// The initial time of the timer.
var time = 120;
// Hide the timer display for now, until the button is clicked.
$timerDisplay.hide();
// Set up a click handler on our $startTimer button.
$startTimer.click(function () {
// When the button is clicked, do the following:
// Set the disabled property to true for our button.
// Effectively the same as <button id="startTimer" disabled>Start Timer</button>
$startTimer.prop('disabled', true);
// Fade in our timer display DIV element.
$timerDisplay.fadeIn();
// Set a timeRemaining variable to the value of the initial time.
var timeRemaining = time;
// Declare an interval function that runs every second.
// Also get reference to the intervalId that it returns so we can kill it later.
var intervalId = setInterval(function () {
// Every time the interval runs (every second), do the following:
// Create a formatted countdown timestamp using the timeRemaining.
var timeStamp = Math.floor(timeRemaining/60) + ':' + timeRemaining%60;
// Set the text of our timer display DIV element to our formatted timestamp.
$timerDisplay.text(timeStamp);
// If the timeRemaining is zero, clean up.
if (timeRemaining === 0) {
// Kill the interval function so it doesn't run again.
clearInterval(intervalId);
// Fade out our timer display DIV element.
$timerDisplay.fadeOut();
// Show the alert informing the user the timer is up.
alert('Time is up, please submit a vote :)');
// Re-enable the startTimer button.
$startTimer.prop('disabled', false);
}
// Otherwise subtract one second from the timeRemaining and allow the interval to continue.
else {
timeRemaining--;
}
}, 1000);
});
});
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 am creating a web page where the user clicks a button as many times as they can in 5 seconds. Currently the timer starts when the page is initially loaded. However, I would like the timer to start when the user first clicks the 'Click' button and is not reset every time the user clicks the button after the first click.
Any ideas on how to do this? Thanks in advance.
HTML button:
<div class='buttonDiv'>
<button onclick='countClicks()' id='click' type="button">Click Me!</button>
</div>
Javascript functions:
/*record clicks*/
var clicks = 0;
function countClicks(){
document.getElementById('click').value = ++clicks;
document.getElementById('result').innerHTML = clicks;
}
/* Timer countdown */
var secs=5;
var counter=setInterval(timer, 1000);
function timer(){
secs--;
if (secs <= 0){
clearInterval(counter);
document.getElementById("click").disabled = true;
document.getElementById("seconds").innerHTML=0;
return;
}
document.getElementById("seconds").innerHTML=secs;
}
Simply declare the counter variable then check if it is set inside the function:
var counter;
function countClicks(){
if( !counter ){//counter is not set
counter = setInterval(timer, 1000);
} else {
document.getElementById('click').value = ++clicks;
document.getElementById('result').innerHTML = clicks;
}
}
I want to make a 5-second countdown inside my button so you can see how much time is left before I submit some content after I click the button. I get the value he has to count down from "data-delay" inside my HTML tag
});
Demo of what I assume you want: http://jsfiddle.net/Lp99cw3q/2/
Firstly,
var b = $(button);
is invalid, I assume you're wanting to access the button attributes, so use:
var b = $('#first');
This then allows you to use b to access everything you need, eg:
var text = b.attr('value');
if you want the timer function to be called on click:
$('#first').click(function() {
timer();
});
which I would then set up as so:
function timer(){
setTimeout(function(){
b.val(text + ' ' + counter); // update the text with the counter
b.attr('data-delay', counter); // update the attribute holding the value
if (counter == 0) {next();} // if finished, call next function
else {counter--; timer();} // decrease the counter and call the timer again after 1s
},1000);
}
function next() {
b.val('Done!');
//whatever happens afterwards
}
Here is the updated/working code.
<input type="button" value="Submit and wait!" id="first" data-delay="5"></input>
var button = $('#first');
var counter = button.attr('data-delay');
var text = button.attr('value');
function timer() {
button.val(text+' '+counter);
if (counter == 0) {
clearInterval(countdownTimer);
button.val("TimeOut");
} else {
counter--;
}
}
var countdownTimer = setInterval('timer()', 1000);
Here is the functionality simply when click btnGo timer will stop and get it's value, if time remaining is not exceed its automatically add +1 to On time total My problem is its not adding it only shows the value below are my codes with live demo
My JS
var sec = $('#timerSec').text() || 0;
var timer;
function startTimer() {
if (timer) clearInterval(timer);
sec = 10;
timer = setInterval(function() {
$('#timerSec').text(sec--);
if (sec == 0) {
clearInterval(timer);
}
}, 1000);
}
$(function() {
startTimer();
$('#btnGo').click(function(){
$(this).fadeOut();
$("#alert").fadeIn();
clearInterval(timer);
var secR = $('#timerSec').text();
var t = $('#alert span').text()
$('#btnCon').fadeIn();
if (secR != 0 ){
var i = t+1;
}
$('#alert span').html(i).show();
});
$('#btnCon').click(function(){
$("#alert").fadeOut();
$("#btnGo").fadeIn();
startTimer();
});
});
My html
<div id="timerSec">10</div> seconds
Go
<div id="alert" style="display:none">
<a href="#" id="btnCon" >Continue</a>
On time = <span>0</span>
</div>
Live Demo jsfiddle
I'm not sure it's functioning as you want it to, but in any case the problem with the addition is that it was treating the text value of the span as a string (which it is). So when you "added" 1 to it, it was actually just concatenating. You can use Number() to fix this. See this updated code.