Stop Countdown Timer Javascript onClick - javascript

Given the Following code:
$('#myButton02').click(function(){
$('#myButton02').hide();
$('#counter').animate({width: 'toggle'});
var count=65;
var counter=setInterval(timer, 1000);
function timer(){
count=count-1;
if (count <= 0){
clearInterval(counter);
return; }
document.getElementById("secs").innerHTML=count + " segs.";}
});
$('#myButton03').click(function(){
recognition.stop();
$('#myButton02').show();
$('#counter').toggle();
});
I can have the following workflow:
User clicks a button, that button gets replaced by another one.
A div appears with a countdown timer of 65 seconds.
If the user clicks the other button (the one wich replaced the first one) the first button appears again hiding the second one and then the appeared div (#counter) dissapears. The problem is, when the user clicks the first button again, the countdown timer goes nuts and starts toggling random numbers instead of starting a new countdown (only if the user clicks it again before the first countdown stops).
How can I make the timer stops the countdown when "#myButton03" gets clicked so it "reboots itself" every time you click "#myButton02" without going nuts?

I agree. Make the counter variable global and have it get reset when you click myButton03. See this fiddle with a modified version of your code for a possible way of doing that:
var count;
var counter;
function resetEverything()
{
$("#counter, #myButton03").hide();
$('#myButton02').show();
clearInterval(counter);
}
$(document).ready(function(){
resetEverything();
$('#myButton02').click(function(){
$('#myButton02').hide();
$('#myButton03').show();
$('#counter').animate({width: 'toggle'});
count=65;
counter=setInterval(timer, 1000);
function timer(){
count=count-1;
if (count <= 0){
clearInterval(counter);
return; }
document.getElementById("secs").innerHTML=count + " secs.";}
});
$('#myButton03').click(function(){
resetEverything();
});
});
http://jsfiddle.net/Xd3UR/
Hope that helps.

Making the counter variable global and then adding the following line to the myButton03
click function should do the trick.
clearInterval(counter);

Related

remove class only one time when add class many times

I have a following code:
btn.onclick = function() {
toast.classList.add('showToast')
setTimeout(function() {
toast.classList.remove('showToast')
}, 3100)
}
Assume at 0s I click a lot of times on button, so maybe at 3.1s I receive a lot of remove handle on toast, this is not what I expect because maybe at 3.2s I click on button one more time toast disappear immediately instead action in 3.1s. I want users could click on button as many time they want, equivalent to addClass() be handled a lot of time but removeClass() only be handled one time corresponding to the last addClass() and the last clicking. How can I do that, or maybe could you give me another way to handle this, thanks
It sounds like you want to cancel any still-active timeout when the button is clicked again. In that case, you need to store the timer ID in a variable outside the function, and then call clearTimeout on that before setting the new timeout.
let timerId;
btn.onclick = function() {
toast.classList.add('showToast')
clearTimeout(timerId);
timerId = setTimeout(function() {
toast.classList.remove('showToast')
}, 3100)
}
Note that as shown above timerId is a global variable, but this is not ideal. Ideally this code is inside some function which would mean timerId does not pollute the global scope. But that depends on information about how your code is architected that you do not show us.
create counter using setInterval()
var counterHandle;
var counter = 0;
btn.onclick = function() {
counter = 0;
clearInterval(counterHandle);
toast.classList.add('showToast');
counterHandle = setInterval(()=>{
counter +=1;
console.log(counter);
if(counter === 3){
toast.classList.remove('showToast');
clearInterval(counterHandle);
}
}, 1000);
}
when the button is pressed many times the counter will always be 0 and when the counter has a value of 3 the command will be executed

Execute Multiple Clicks

I am trying to click a button multiple times. Each time the button is clicked, it loads for 1 second, reappears and is able to be clicked again. I want to click this button 5 times.
for(i=0;i<5;i++)
$('.class').click();
The above code only executes one click.
Even this code, execute only one click.
for(i=0;i<5;i++)
setTimeout(() => $('.class').click(),2000);
If I do the step manually , that is if I enter $('.class').click() to the console five times, it works. Any idea as to why ?
Multiply the delay with the i since for loop does not wait for executing the setTimeout callback.
for(i = 1;i <= 5; i++)
setTimeout(() => $('.class').click(),i * 2000);
Another way is to use setInterval method along with clearInterval.
// variable for count
var i = 0;
// reference for clearing interval
var inter = setInterval(()=>{
// trigger click event
$('.class').click();
// increment and check value reached to `5`
// if `5` then clear the interval
if(++i == 5) clearInterval(inter);
},2000);
If you log the click event on button, it is clicked 5 times, even with your first example
$('.button').on('click', function () {
console.log('clicked')
})
for(i=0;i<5;i++)
$('.button').click();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button"></button>

Onclick load page in Div and change text

I have this button and what it currently does is onclick it changes the text from text1 to text2 Below is the button and the script which achieves this.
Button
<button type="button" id="buttonsend" style="margin-top:-7px;" class="btn btn-default">
<span>text 1</span>
<span style="display:none">text 2</span>
</button>
<div id="load"></div>
Javascript
$('#buttonsend').click(function() {
$('span',this).toggle();
});
What I want it to also do is load a page in the #load div only once its clicked and also refresh the page loaded in the div every 10 seconds.
Example
Once the button is clicked the text is changed to text2 and the #load div loads the demo.html page and refreshes this page every 10 seconds. once the button is clicked again the #load div stops refreshing the page and the text returns to text1. I'm really sorry for making this almost a request but I'm having some difficulties achieving this.
I have coded this script below which refreshes a page loaded in a div every 10 seconds however it loads before the button is clicked so I'm not sure how to get it work once the button is clicked and when the button is clicked again to stop refreshing. Thankyou.
Refresh Script
$(document).ready(function(){
setInterval(function(){
$("#load").load('/demo.html')
}, 10000);
});
You could use a boolean variable for this, which you toggle when the button is clicked, and in your interval callback you just check whether it is set before reloading:
var reload = false;
$('#buttonsend').click(function() {
reload = !reload;
// other actions...
});
$(document).ready(function(){
setInterval(function(){
if (reload) $("#load").load('/demo.html')
}, 1000); // or 10000 if you want 10 sec.
});
Try using variables to keep the state of your button:
$(document).ready(function(){
var button_state = 'state1';
function toggleButtonState() {
if(button_state == 'state1') button_state == 'state2';
else button_state == 'state1';
}
$('#buttonsend').click(function() {
toggleButtonState();
$('span',this).toggle();
});
setInterval(function(){
if(button_state == 'state2') $("#load").load('/demo.html');
}, 10000);
});
While Wikiti's and trincot's answers are correct, I believe it's better to disable the loop while it's not used, using clearInterval. This will make sure that content will load the moment when user presses the button - otherwise, like in Wikiti's and trincot's answers, user may miss the loop iteration and click the button when there are 9 seconds to the next iteration, so he will have to wait 9 seconds for the content to begin loading.
$(document).ready(function(){
var timer = "none";
function startLoop() {
timer = setInterval(function(){
$("#load").load('/demo.html');
}, 10000);
}
function toggleButtonState() {
if (timer === "none") { startLoop(); }
else { clearInterval(timer); timer = "none"; }
}
$('#buttonsend').click(function() {
toggleButtonState();
$('span',this).toggle();
});
});
If you give text2 and id you can see if it is visible or not, or wrap it in a div, I had a similar need to have a countdown and to pause when the div was visible. Can't remember where I took the below from. Basically counts down from 300, but pauses when the div called 'callUpdateWrap' is visible. I also had it update a timer on the page itself (see way down the page):
JS:
function refreshpage(interval, countdownel, totalel){
var countdownel = document.getElementById(countdownel)
var totalel = document.getElementById(totalel)
var timeleft = interval+1
var countdowntimer
function countdown(){
if (!$('#callUpdateWrap').is(':visible')) {
timeleft--
}
countdownel.innerHTML = timeleft
if (timeleft == 0){
clearTimeout(countdowntimer)
window.location.reload()
}
countdowntimer = setTimeout(function(){
countdown()
}, 1000)
}
countdown()
}
window.onload = function(){
refreshpage(300, "countdown") // refreshpage(duration_in_seconds, id_of_element_to_show_result)
}
HTML:
<h2>Page will Refresh in <b id="countdown"></b> seconds</h2>
Quick Edit:
If you need the timer to reset, where the div is checked if visible, you could add an else to set the time back to 10.

Wait for keypress with timeout

In an experiment I'm coding, on every trial, I need to display a stimulus (search array) and then wait for a maximum of 5 seconds for the subject to respond with a keypress. If a key is pressed, the next trial begins immediately or else after 5 seconds.
I just want to know if I can code up something like this in JavaScript, and if so, how should I code up the experiment? Also, I should be able to store the identity and timestamp of the key pressed.
The flow of your experiment, as I understood them, are this:
Show Stimulus
Check for keypresses repeatedly
If 5 seconds have passed, show next stimulus
If key was pressed, store keypress in array, then show next stimulus.
To do this, I would use Keypress, a JS library for catching input.
You would first want to define your stimuli
E.g.:
var stimuli = ["Apple","Orange","Keira Knightley","Banana"];
You would then want to set up your event listeners. These will log your keypresses for you.
var listener = new window.keypress.Listener();
var results = [];
listener.simple_combo("shift s", function() {
results.push("You pressed shift and s");
});
Then you want to set up the timing system. I would use a setInterval() function to increment the position in the array that the subject is in.
var pos = -1; //Arrays start at 0, and you want to run this function to start.
function nextStim() {
pos = pos + 1;
myDiv.innerHTML = stimuli[pos]
}
var results = [];
listener.simple_combo("shift s", function() {
results.push("The stimulus was: " + stimuli[pos] + "And you pressed Shift + S" );
});
setInterval(nextStim,5000);
<script>
var timeout;
timeout = setTimeout(next, 5000); //execute function "next" after 5000 miliseconds
//With jQuery
//$("#element").on("keypress", function(){ clearTimeout(timeout); next();} );
//Without jQuery
function elementOnKeypress()
{
clearTimeout(timeout); //don't execute "next" after 5000 (or less) ms
next(); //run "next"
}
function next()
{
//your code ..
}
</script>
<element onkeypress="elementOnKeypress();"></element><!-- element is your html-element to be keypressed -->

how can I rearrange this code so my setInterval stops looping infinitely?

I'm trying to make a simple flip-card/memory match (like from super mario brothers 3) game in HTML/Javascript and am having a slight issue with the setInterval command.
Here is a link to the full code: http://jsfiddle.net/msfZj/
Here is the main issue/main logic of it:
if(click == 2) //denotes two cards being clicked
{
if(flippedArray[1].src === flippedArray[0].src) // if click 1 == click 2 then refer to function 'delayMatch' which sets click 1 and 2 cards to not be displayed
{
window.setInterval(function() { delayMatch() }, 500);
console.log("EQUAL");
}
else
{
window.setInterval(function() { delayNoMatch() }, 500); // if click 1 != click 2 then display card.png
console.log("NOT EQUAL");
}
function delayMatch() //function for matching pairs
{
flippedArray[0].style = "display:none;";
flippedArray[1].style = "display:none;";
}
function delayNoMatch() //function for non-matching pairs
{
flippedArray[0].src = "card.png";
flippedArray[1].src = "card.png";
}
click = 0; // when clicked two cards set click back to zero
}
The first two cards I click on always work: but from that point onward the setInterval keeps running the function over and over again in an endless loop every 500ms.
I'd be extremely appreciative if anybody can point my in the right direction on how I can do this properly.
Thank you very much for your time.
It looks like you need setTimeout, which only runs once?
window.setTimeout(function() { delayMatch() }, 500);
Otherwise, you need to clear the interval with clearInterval(i), but first set "i" using the return value of setInterval:
var i = window.setInterval(function() { delayMatch() }, 500);
Here's a demo (I JQuerified it a bit for JSFiddle).
You're going to want to go with setTimeout() instead of setInterval()
A handy function when you use setTimeout is clearTimeout. Say you want to set a timer, but maybe want a button to cancel
var timer = setTimeout(fn,1000);
//later maybe
clearTimeout(timer);

Categories