Execute Multiple Clicks - javascript

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>

Related

Using JavaScript, how do I get this code to autofill Username & click button, delay, or wait, then autofill Password & click log in?

document.getElementsByName("Username")[0].value = 'FamilyGuy'
function myFunction(){
//pag 1, delay a second. Giving user name time to fill
document.getElementById("NextButton").click();
}
//delay
setTimeout(myFunction, 1000);
function myFunction(){
//page 2, delay a second. Giving passwrd time to fill befor logging in
document.getElementsByName("Password")[0].value = 'this1sth3p4ssw0rd!'
}
//delay
setTimeout(myFunction, 1000);
document.getElementById("LoginButton").click();
//I am using this extension using this extension
[1]: https://i.stack.imgur.com/LNMiJ.png
setTimeout is an asynchronous function. It doesn't pause the execution of code that follows it.
This means that, in your example code, the two timeouts will run simultaneously, and your login button will be pressed immediately. To fix this, put the second timeout at the end of your first function, rather than in the main body of code. Also put the pressing of the login button inside the second function.
document.getElementsByName("Username")[0].value = 'FamilyGuy'
function myFunctionB(){
//page 2, delay a second. Giving passwrd time to fill befor logging in
document.getElementsByName("Password")[0].value = 'this1sth3p4ssw0rd!'
document.getElementById("LoginButton").click();
}
function myFunctionA(){
//pag 1, delay a second. Giving user name time to fill
document.getElementById("NextButton").click();
//delay
setTimeout(myFunctionB, 1000);
}
//delay
setTimeout(myFunctionA, 1000);
I don't know the way the NextButton operates, but the use of a delay to wait until the Username value changes is probably unnecessary. Consider using the following code:
function myFunction(){
document.getElementsByName("Password")[0].value = 'this1sth3p4ssw0rd!'
document.getElementById("LoginButton").click();
}
document.getElementsByName("Username")[0].value = 'FamilyGuy'
document.getElementById("NextButton").click();
//delay
setTimeout(myFunction, 1000);
This may be one possible implementation to achieve the below-described (what is assumed to be the desired) objective:
A screen with input-boxes username, password and buttons 'Next', 'Login' is rendered
After waiting for some time (say 1.5 seconds), username is auto-populated
Another delay of 2 seconds and 'Next' button click is programatically triggered
After delay of 2 seconds, password is auto-populated
Finally, another delay of 1 second and 'Login' button is programatically triggered.
The time-delays are just randomly assigned in the snippet and may be altered as required.
It would definitely helpful to understand the context within which this is being used - to cater a more suitable answer.
const btnClicked = name => console.log(`${name} button clicked `);
setTimeout(
() => {
document.getElementById("Username").value = 'FamilyGuy';
setTimeout(
() => {
document.getElementById("NextButton").click();
setTimeout(
() => {
document.getElementById("Password").value = 'this1sth3p4ssw0rd!';
setTimeout(
() => {
document.getElementById("LoginButton").click();
},
1000
)
},
2000
)
},
2000
)
},
1500
);
<html>
<body>
<input id='Username' />
<button id='NextButton' onclick='btnClicked("Next")'>Next</button>
<input id='Password' />
<button id='LoginButton' onclick='btnClicked("Login")'>Login</button>
<script src='script.js'></script>
</body>
</html>

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

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

Stop Countdown Timer Javascript onClick

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

Categories