How do make a count down inside the button? - javascript

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

Related

read div and check for a click condition

let timer = document.querySelector("#timer");
var counter = 3;
function myFn() {
counter--
if (counter === -1) {
counter = 3
}
timer.innerText = counter
}
btn.onclick = function() {
text.innerHTML += 'clicked' + '<br>'
}
var myTimer = setInterval(myFn, 1000);
<div id="timer"></div>
<button id="btn">Button</button>
<div id="text"></div>
I'm trying with this small code to read the div#timer every second and check for a click condition in console.log() F12. It gives me different error in every way I try to do it.
let timer = document.querySelector("#timer");
let btn = document.querySelector("#btn");
setInterval(() => {
console.log(timer.textContent)
if (timer.textContent === '0') {
btn.click()
}
}, 1000);
Consider the following jQuery example.
$(function() {
var timer = 0;
var counter = 3;
var timeObj = $("#timer");
var btnObj = $("#btn");
var txtObj = $("#text");
var interval;
function myFn() {
if (--counter >= 0) {
txtObj.append("Clicked<br />");
} else {
clearInterval(interval);
}
}
interval = setInterval(function() {
timeObj.html(++timer);
}, 1000);
btnObj.click(myFn);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer">0</div>
<button id="btn">Button</button>
<div id="text"></div>
You will want to use setInterval() and not setTimeout().
The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
See more: https://developer.mozilla.org/en-US/docs/Web/API/setInterval
Using the -- and ++ before the variable will also apply the change before it is used.
The decrement operator (--) decrements (subtracts one from) its operand and returns the value before or after the decrement, depending on where the operator is placed.
Adjusting the logic here can also ensure that the button click does allow the user to keep performing actions.

set Interval function giving output for previous parameter [duplicate]

So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?
Here's my .js file and the calls I'm making are
input type="button" value="generate" onClick="generation();
input type="button" value="Infinite Loop!" onclick="setInterval('generation()',1000);"
input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.
setInterval returns a handle, you need that handle so you can clear it
easiest, create a var for the handle in your html head, then in your onclick use the var
// in the head
var intervalHandle = null;
// in the onclick to set
intervalHandle = setInterval(....
// in the onclick to clear
clearInterval(intervalHandle);
http://www.w3schools.com/jsref/met_win_clearinterval.asp
clearInterval is applied on the return value of setInterval, like this:
var interval = null;
theSecondButton.onclick = function() {
if (interval === null) {
interval = setInterval(generation, 1000);
}
}
theThirdButton.onclick = function () {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
}
Have generation(); call setTimeout to itself instead of setInterval. That was you can use a bit if logic in the function to prevent it from running setTimeout quite easily.
var genTimer
var stopGen = 0
function generation() {
clearTimeout(genTimer) ///stop additional clicks from initiating more timers
. . .
if(!stopGen) {
genTimer = setTimeout(function(){generation()},1000)
}
}
}
Live demo
This is all you need!
<script type="text/javascript">
var foo = setInterval(timer, 1000);
function timer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
$(document).on("click", "#stop_clock", function() {
clearInterval(foo);
$("#stop_clock").empty().append("Done!");
});
</script>

Reset variable in Javascript on execute?

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

Change background images using setTimeout

I have 31 images and I want to display them one after another as the background of a div. I only want it to change when the user hovers over the div. My problem right now is that it just flips through all the images really fast. I am attempting to use setTimeout, but it isn't working. How can I make the delay work?
The name of the div is About_Me_Block and the images are called frame1.gif,frame2.gif ...etc
Here is my code:
function changeImg(counter) {
$('#About_Me_Block').attr("style", "background-image: url(playGif/frame" + counter + ".gif);");
}
$(document).ready(function() {
var hoverAnimate = []
"use strict";
$('#About_Me_Block').mouseenter(function() {
hoverAnimate[0] = true;
var counter = 0;
while (hoverAnimate[0]) {
console.log(counter);
setTimeout(changeImg(counter), 1000);
counter++;
if (counter === 32)
hoverAnimate[0] = false;
}
});
$('#About_Me_Block').mouseleave(function() {
hoverAnimate[0] = false;
$(this).attr("style", "background-image: url(play.jpeg);");
});
});
setTimeout doesn't wait for the function to end, it works lile threading in other languages.
To achieve a what you want, you need to call setTimeout from the changeImg function.
var counter = 0;
$(document).ready(function() {
var hoverAnimate = []
"use strict";
$('#About_Me_Block').mouseenter(function() {
hoverAnimate[0] = true;
counter = 0;
changeImg();
});
$('#About_Me_Block').mouseleave(function() {
hoverAnimate[0] = false;
$(this).attr("style", "background-image: url(play.jpeg);");
});
});
function changeImg() {
$('#About_Me_Block').attr("style", "background-image: url(playGif/frame" + counter + ".gif);");
counter++;
if (counter < 32 && hoverAnimate[0]) {
setTimeout(changeImg, 1000);
} else {
hoverAnimate[0] = false;
}
}
the reason they happen all at once is because while statement doesn't have delay, so all setTimeout will be set up at the same time, thus, calling changeImg all at once.
To solve this problem, you can replace setTimeout with setInterval. Instead of using while, you can just call setInterval like
var counter = 0;
var myTimer = setInterval(changeImg, 1000);
and update counter inside changeImg every time it gets called. After looping, don't forget to
clearInterval(myTimer)
It seems you need to read up on how setTimeout works. It essentially places a reminder to run a function after a given amount of milliseconds have passed. So, when you do setTimeout(changImg(counter), 1000) you are calling changImg(counter) which returns undefined. Therein producing this setTimeout(undefined, 1000) which is why it flips really fast.
So, you can use bind to allow the function to be called later with that parameter built in. Also, make sure you remove the reminders once done with clearTimeout.
function changeImg(counter) {
$('#About_Me_Block').attr("style", "background-image: url(playGif/frame" + counter + ".gif);");
}
$(document).ready(function() {
var hoverAnimate = false, id;
function loop(counter) {
if(hoverAnimate || counter < 32) {
changeImg(counter);
id = setTimeout(loop.bind(this, counter++), 1000);
}
}
$('#About_Me_Block').mouseenter(function() {
hoverAnimate = true;
id = setTimeout(loop.bind(this, 0), 1000);
});
$('#About_Me_Block').mouseleave(function() {
hoverAnimate = false;
// Don't want a reminder for a random counter to wake up.
clearTimeout(id);
$(this).attr("style", "background-image: url(play.jpeg);");
});
});
Two methods for timers - setTimeout and SetInterval (single / repeating)
// setInterval is also in milliseconds
var intervalHandle = setInterval(<yourFuncToChangeImage>,5000);
//this handle loop and make example loop stop
yourelement.yourEvent = function() {
clearInterval(intervalHandle);
};

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

Categories