button count down enable - javascript

I have a button inside a modal that have a countdown, at first it is disabled (is true), but after the countdown it turns disable.
If I leave the button countdown untill the end, and then I test it again (closing my modal and open it again), it starts the countdown over again, it works fine up to now.
But it has a strange bug.
If in the middle of the countdown, I close the modal and then open it again, my countdown restarts but it goes imedially to the end of the countdown, it doesn't go through all the numbers.
Here is my code:
html:
<button
ng-click="wizardCtrl.callModal()"
id="btn-unblock"
ng-disabled="wizardCtrl.unblock"
type="button"
class="btn btn-medium #{{ wizardCtrl.btn }}"
href=""
>
Wait #{{wizardCtrl.message}} seconds
</button>
controller:
vm.unblock = true;
function unblockButton() {
debugger;
vm.c = 5;
vm.message = vm.c;
var timer = $interval(function() {
vm.message = vm.c;
vm.c--;
if(vm.c<0) {
$interval.cancel(timer);
vm.unblock = false;
angular.element('#btn-unblock').text("Desbloquear e Ver");
vm.btn = "btn-green";
}
}, 1000);
}

When closing the modal, you should also abort the interval. It is still running when you open the modal up again, so it will affect the second modal. Alternatively check if an interval is set and clear it before opening.

You need to reset the timer and the button before you start the timer.
vm.unblock = true;
// Make your timer variable global
var timer = null;
function unblockButton() {
debugger;
vm.c = 5;
vm.message = vm.c;
// Clear old timer
$interval.cancel(timer);
// Block the button
vm.unblock = true; // Check this part of code...
vm.btn = "btn-red"; // This too...
// Start new timer
timer = $interval(function() {
vm.message = vm.c;
vm.c--;
if(vm.c<0) {
$interval.cancel(timer);
vm.unblock = false;
angular.element('#btn-unblock').text("Desbloquear e Ver");
vm.btn = "btn-green";
}
}, 1000);
}

Related

How can I override a JavaScript variable when page is visible again?

When visiting a web page I want to declare a start time and send an AJAX request when the user leaves the site. It works like expected but when changing the tab or minimizing the browser the start time remains the same as when the user accessed the web page. I thought I could override the start time by declaring it within a function which is fired when the tab is active again but with no success.
Here is my code so far:
$(document).ready(function() {
var starts = Math.ceil(Date.now() / 1000);
//declare new start time when user returns
document.addEventListener('visibilitychange', function() {
if(!document.hidden) {
var starts = Math.ceil(Date.now() / 1000);
}
});
//AJAX
//value of old starts is used here instead of new declared starts
...
});
Does anyone have a solution for this?
Try document.visibilityState === 'visible' so your code will look like this:
$(document).ready(function() {
var starts = Math.ceil(Date.now() / 1000);
//declare new start time when user returns
document.addEventListener('visibilitychange', function() {
if(document.visibilityState === 'visible') {
var starts = Math.ceil(Date.now() / 1000);
}
});
});
Read more about it here:
https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event
const timer = document.querySelector("#timer");
window.addEventListener('DOMContentLoaded', () => {
startTimer(); // starttime on load
});
let intervalID = null;
let timerValue = 0;
const startTimer = () => {
intervalID = setInterval(() => {
timerValue++;
timer.innerText = timerValue;
}, 1000);
}
const stopTimer = () => {
clearInterval(intervalID);
}
document.addEventListener('visibilitychange', () => {
if (document.hidden) { // codition for browser tabs is active or minimize
stopTimer(); // stop timer when you leave tab minimize it on
return;
}
startTimer(); // start timer when you comback to tab maximize it
})
<div class="container">
<h2>time spend in seconds:<span id="timer">0</span>
<h2>
</div>

Counter speed increases when the start button is clicked again

When the start button is clicked once, everything works perfectly fine. However, when the start button is clicked multiple times (by accident for example), the speed of the counter increases and the stop button doesn't seem to work any more!
Why is this happening? And what can I do to prevent the start button (if clicked accidentally) from increasing the speed of the timer when it is already running?
<button id="startBtn" onclick="startTimer()">Start</button>
<button id="stopBtn" onclick="stopTimer()">Stop</button>
<h2 id="timer"></h2>
<script>
let myCounter
function startTimer() {
myCounter = setInterval(counter, 200);
}
function stopTimer() {
clearInterval(myCounter);
}
let i = 0;
function counter() {
document.getElementById("timer").innerHTML = i++;
}
</script>
Welcome to StackOverflow.
Within your question, it's unclear if you want the timer to reset if the user clicks the start button again, however with my answer, I came to the conclusion that you didn't.
Here's a modified version of startTimer() which utilizes a guard clause to check if an interval already exists (and if so, don't start again)
function startTimer() {
// Guard clause! If the counter exists, exit the function!
if(myCounter) {
return
}
myCounter = setInterval(counter, 200);
}
A tiny update of the stop function is also needed to set myCounter to null after the counter is stopped:
function stopTimer() {
clearInterval(myCounter);
// Set the counter to Null, because it is still declared even though it has no value! (try removing this line and see what happens when you hit start again)
myCounter = null;
}
Hope this helped :)
I added a variable that can helps you detect if the counter is already clicked or not, with the condition of that variable, you can have what you want, I edited your code.
<button id="startBtn" onclick="startTimer()">Start</button>
<button id="stopBtn" onclick="stopTimer()">Stop</button>
<h2 id="timer"></h2>
<script>
let myCounter
let clicked = false;
function startTimer() {
if(!clicked){
myCounter = setInterval(counter, 200);
}
clicked = true;
}
function stopTimer() {
if(clicked){
clearInterval(myCounter);
}
clicked = false;
}
let i = 0;
function counter() {
document.getElementById("timer").innerHTML = i++;
}
</script>
You could simply disable the start button once clicked, and re-enable it when the stop button is clicked.
let i = 0;
let myCounter;
let startBtn = document.getElementById('startBtn');
let stopBtn = document.getElementById('stopBtn');
let timer = document.getElementById('timer');
function startTimer() {
startBtn.disabled = true;
stopBtn.disabled = false;
myCounter = setInterval(counter, 200);
}
function stopTimer() {
startBtn.disabled = false;
stopBtn.disabled = true;
clearInterval(myCounter);
}
function counter() {
i++; timer.value = i;
}
startBtn.addEventListener('click', startTimer);
stopBtn.addEventListener('click', stopTimer);
<button id="startBtn">Start</button>
<button id="stopBtn" disabled>Stop</button>
<h2><output id="timer">0</output></h2>
As an added measure, you can even hide the disabled button so only the active one is shown.
button:disabled {
display: none;
}

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.

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