Reset variable in Javascript on execute? - javascript

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);

Related

Jquery Timer that starts and stops with same button

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.

Set a background timer in javascript

I'm trying to prevent users in Dynamics 365 / CRM from quickly clicking on the same button, thus initiating a synchronous, window-blocking event.
We were able to fix this in IE, but Chrome seems to "remember" the button clicks - and then initiate the same event, again and again, synchronously (as is expected).
I had thought about creating a background timer, that will be initiated on the first button click, which will turn a variable as 'True' until the timer finishes, then turning the variable as 'False'.
During those X seconds in which the variable is set to true, subsequent button clicks will fire the event, but not proceed any further than a few lines where the function will check if the variable is set to true or false.
This is my (not working) code so far:
function startTimer(duration) {
isTimerOn = true;
var timer = duration, seconds;
setInterval (function () {
seconds = parseInt(timer % 60, 10);
seconds = seconds < 10 ? 0 + seconds : seconds;
if (--timer < 0) {
timer = duration;
}
}, 500);
isTimerOn = false;
};
var isTimerOn = false;
function createWordSummary() {
if (isTimerOn) {
return;
}
try {
startTimer(3);
// Logic here
Would love some help, thanks in advance!
You can try something like this:
let disabled = false;
function startTimer(s) {
disabled = true;
setTimeout(function() {
disabled = false;
}, s * 1000);
}
function createWordSummary() {
if ( disabled ) return;
startTimer(3);
console.log('check');
}
<button onclick="createWordSummary()">Check</button>
Hope it helps!

localStorage not clearing when using setInterval() for JS timer

I am working on a personal project and I am making use of JS to implement a simple countdown timer. There are several requirements that need to be addressed:
- The timer starts when the page is loaded
- When the user wishes to leave the page, they are warned that their progress will be lost, hence, the timer is reset.
I am making use of localStorage to keep the remaining time, since every time the user submits a form that is on the page, the page is reloaded (I understand that it is better to use AJAX, but for the time being, I am trying to make it work properly as it is). You can see my code below:
var submit_form;
var timeLeft;
function startTimer(duration, content) {
var timer = duration, min, sec;
setInterval(function () {
if (--timer < 0) {
//redirect here;
submit_form = true;
localStorage.removeItem("remainingTime");
window.location.replace("some url");
} else {
min = parseInt(timer / 60, 10);
sec = parseInt(timer % 60, 10);
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
localStorage.setItem("remainingTime", timer);
console.log(timer);
content.textContent = min + ":" + sec;
}
}, 1000);
}
window.onload = function () {
submit_form = false;
console.log(submit_form);
if (localStorage.getItem("remainingTime")) {
timeLeft = localStorage.getItem("remainingTime");
} else {
timeLeft = 60;
}
var display = document.querySelector('#time');
startTimer(timeLeft, display);
};
window.onbeforeunload = function () {
if (submit_form != true) {
localStorage.removeItem("remainingTime");
window.localStorage.clear();
return "You will lose all your progress!/nAre you sure you want to quit?";
}
};
'submit_form' is used for controlling when 'onbeforeunload' gets triggered - When the user submits the form, it shouldn't trigger.
<button type="submit" name="submit" value="Search" id="search-button" onclick="submit_form = true;">Submit</button>
The issue that I am facing, which is killing me, is that sometimes when the user tries to leave the page, i.e. 'onbeforeunload' is triggered, the localStorage doesn't always clear. Therefore, when they come back to the page, the timer doesn't start from the beginning, but instead, from where they left off.
I have tried a few variations of the code above, and my best guess is that setInterval() might be the reason for localStorage not clearing every time.

Hide Button When Clicked, Show Button When Timer Runs Out

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);
});
});

activate timer on first click of button

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;
}
}

Categories