Insert a 5-second delay in the JavaScript code before triggering the click event on the next button

Currently, I have a JavaScript code in place that is fairly straightforward. The webpage contains about 100 buttons with the class button, and I am successfully simulating clicking each one of them systematically.

However, I would like to introduce a delay of 5 seconds between each button click for better user experience.

var mybtn = document.getElementsByClassName('.button');
for( var i=0; i<100; i++ ) {
    mybtn[i].click();
}

Answer №1

If you're looking to achieve that functionality, consider using the setInterval method.

Instead of explicitly defining the value as 100, utilize the length property.

Avoid relying on getElementsByClassName as it is not considered standard practice. Opt for document.querySelectorAll instead, as it is widely supported across browsers.

var mybtn = document.querySelectorAll('.button');
var i = 0;

var timer = setInterval(function() {
     if( i < mybtn.length) {
         mybtn[i].click();
         console.log("Click handler for button " + i + " fired");
     } else {
         clearInterval(timer);
     }
     i = i + 1;
}, 5000);
<div class="button">Hi1</div>
<div class="button">Hi2</div>
<div class="button">Hi3</div>
<div class="button">Hi4</div>
<div class="button">Hi5</div>

Answer №2

Is this what you were looking for?

//var buttons = document.getElementsByClassName('.button'); // Not standard
var buttons = document.querySelectorAll('.button');

function clickButton(index) {
    mybtn[index].click();
    if(index < buttons.length) {
        setTimeout("clickButton(" + (index+1) + ");", 5000);
    }
}

setTimeout("clickButton(0);", 5000);

In order to test the code, I included alert():

//var buttons = document.querySelectorAll('.button');

function clickButton(index) {
    //mybtn[index].click();
    alert("button" + index);
    if(index < 100) {
        setTimeout("clickButton(" + (index+1) + ");", 5000);
    }
}

setTimeout("clickButton(0);", 5000);

Answer №3

Utilize the setInterval method to automatically trigger the click event every 10 seconds.

Here is an example:

setInterval(function(){ myButton[i].click(); }, 10000);

Answer №4

If you're open to exploring alternative libraries for solving this issue, I recommend considering Kristopher Michael Kowal's Q library. This library allows you to utilize promises through Array.prototype.reduce, facilitating the iteration and resolution of promises when they are required.

DEMO

// Retrieving all buttons
var buttons = document.querySelectorAll('.button');

// Adding Click Event Handlers
Array.prototype.forEach.call(buttons, registerButtonClickHandlers);

// Triggering button click
Array.prototype.reduce.call(
  buttons,
  reduceButtonPromises , 
  Q.when()
);

function registerButtonClickHandlers(button) {

  button.addEventListener('click', function() {
    // Display end time
    console.timeEnd(button.innerHTML);
  });

}

function reduceButtonPromises(promise, button) {

  // Register promise callback
  return promise.then(function() {

    // Create deferred object
    var deferred = Q.defer();

    setTimeout(function() {
      // Set start time
      console.time(button.innerHTML);
      // Simulate button click
      button.click();
      // Resolve the promise to trigger the next one
      deferred.resolve();
    }, 100);

    // Return promise
    return deferred.promise;

  });

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The MIME type for .rar and .tar files is not specified

Why is it that Javascript (Windows 8.1, Firefox) doesn't seem to recognize mime types for .tar files or .rar files, among others? Is there a way to fix this issue without resorting to unconventional methods? I really need to be able to get the mime ty ...

Navigating through Index in #each in emberjs

Take a look at the code provided below: http://jsbin.com/atuBaXE/2/ I am attempting to access the index using {{@index}}, but it doesn't seem to be compiling. I believe that handlebars should support this feature: {{#each item in model}} {{@index} ...

The functionality of Jquery autocomplete _renderItem appears to be malfunctioning

There seems to be an issue with the _renderItem function as it is not executing at all. I even tried using console.log to debug but no messages are being printed. I also attempted using various attributes like 'autocomplete', 'ui-autocomplet ...

JavaScript code for displaying data sequentially one at a time

Hey there, I've developed a function that pulls data from a jsonp file. However, I'm looking to display this data one by one - starting with the vendor's name followed by their policyUrl. If you want to check out the source code, click on t ...

The Power of Asynchronous Programming with Node.js and Typescript's Async

I need to obtain an authentication token from an API and then save that token for use in future API calls. This code snippet is used to fetch the token: const getToken = async (): Promise<string | void> => { const response = await fetch(&apos ...

What is the process for generating an array of arrays in a React component?

I'm currently working on developing a word-guessing game similar to Wordle using React. The interesting twist in this game is that players have the ability to choose both the number of attempts allowed and the length of the word they are trying to gue ...

Deactivate PyV8's automatic garbage collection functionality

I am currently experiencing an issue that appears to be stemming from the interaction between Python and PyV8's garbage collection processes. To temporarily address this problem, I have disabled Python's garbage collection and implemented a worka ...

The requested resource at http://127.0.0.1:8000/storage/profiles/ could not be located (Error 404: Not

I have successfully implemented a feature on my website that allows users to upload their avatar picture using Vue.js and Laravel as the backend. The image is stored in the storage directory, and I can display it on the user's profile page using Vue.j ...

What is the method for accessing the Redux store content directly in the console, without using any developer tools

By utilizing React Devtools, I am able to access the store by: $r.store.getState() Is there an alternate method to retrieve the store without using React Devtools? ...

Regular expression in Javascript to match a year

I'm still learning javascript and I have a question. How can I determine if a specific piece of text includes a four digit year? Here's an example: var copyright = $('#copyright').val(); if \d{4} appears in copyright: take ac ...

Exploring AngularJS ng-repeat features for custom attribute settings

I'm currently facing a challenge in removing multiple repetitive divs by utilizing ng-repeat. <!-- I have 21 of these --> <div class="table-row"> <span class="glyphicon glyphicon-wrench"></span> <label>Chlo ...

Experimenting with applying jquery .slideDown() to multiple classes in order to create dynamic animations

I am facing an issue while using .slideDown() with multiple classes. I want only one class to toggle/dropdown at a time, but currently when I press the button, all classes show up instead of just the one I want to display. How can I achieve this? Here is ...

Having issues with the functionality of the Previous/Next button in my table

I am facing a challenge with my table as I am trying to include previous/next button for users to navigate through it. However, the interaction doesn't seem to be functioning properly, and I suspect that I need to establish a connection between the bu ...

"Encountering an issue with Express.json where it fails to parse the

Receiving JSON POST data from an IoT API that includes multipart form-data. Occasionally, an image file may be included but I only want to focus on the JSON part: POST { host: '192.168.78.243:3000', accept: '*/*', 'content-le ...

How can I ensure that the form submit event is delayed until the onChange event is completed when using jQuery?

Imagine a scenario where a textbox on a webpage has a 'change' event attached to it using jQuery. $('.myFormClass').on('change', '.amount', function () { // An AJAX call is made here, and the respons ...

Displaying the most recent queries retrieved from a search API

Our web application built on angular.js utilizes a REST search API to query users within the system. The endpoint for searching users is: search/user?q='abc' Upon revisiting the web application, we aim to display the user's recent search ...

Are elements in React Native PanResponder capable of being clicked?

While I have movable panresponders, I also require the ability to click on one for an onPress event. Is it achievable? At present, they are <View> elements. If I attempt to switch them to <TouchableOpacity> or a similar element, it results in ...

Guidelines for creating an auto-scrolling React Native FlatList similar to a Marquee

I currently have a FlatList component set up in my project. <FlatList horizontal data={data} key={(item, index) => index.toString()} ListHeaderComponent={listHeader} renderItem={ // renderin ...

Ways to completely eliminate a global component in VueJS

I have a unique component named button-widget that has been globally registered. Vue.component('button-widget', { template: `<button>My Button</button>` }) Now, I am wondering how I can permanently delete this component. I do ...

Using asynchronous JavaScript (AJAX) to request a file to be processed on the client-side

I have a query that I need help with: My goal is to retrieve a file from the server after it has undergone input-dependent processing through an AJAX request (such as using jQuery). However, I don't want to directly offer this file for download in th ...