Invoke the onClick function within a setInterval loop

My onClick function is functioning correctly. However, I want to run it periodically using setInterval after it's been triggered by a click event. Here's my attempt at modifying the code:

    var clickData;
    var isClicked=0;

    function onClick(e) {
      console.log("OnClick called")
      if(isClicked==0){
        clickData = this;
        isClicked = 1;
        console.log(clickData);
      }

      let empID = clickData.options.empID;
      let reqURL = baseurl  + API_KEY + "&MonitoringRef=" + empID;

      $.ajax({
          type: "GET",
          dataType: "jsonp",
          url: reqURL,
          success: success2,

        });

    }

    if(isClicked==1){
      var f = onClick;
      f.paramater1 = clickData;
      setInterval(f, 500); 
    }

    function success2(json2){
      console,log(json2);
      //Do something with json2...
    }

I made changes to calling the function from setInterval based on one of the solutions found here.

The issue seems to be related to passing parameters to the function. Is there a solution for this?

Answer №1

The issue arose from establishing the interval within the function itself, leading to an endless cycle of interval calls which prevented it from functioning correctly. To work around this problem, you can implement the following solution:

Create a separate function and utilize setTimeout when calling it from onClick:

function onClick(e) {
   // Your onClick function implementation...

   // Incorporate this line in your onClick function to trigger the subsequent function that sets up the interval
   setTimeout( function() { startInterval(clickData); }, 1);
}

Within the startInerval function, you are able to invoke onClick; however, in order to avoid accumulating intervals, I introduce a flag to ensure that the interval is only created once:

var checkFlag = false;
function startInterval(clickData){
   if(checkFlag === false){
      checkFlag = true;
      setInterval(function(){onClick(clickData);}, 500);
   }
}

Answer №2

To implement a function that runs twice per second when a button is clicked, you can add a click listener to the button and then remove it once the interval is set:

const btn = document.getElementById("SPECIFY-YOUR-BUTTON-ID-HERE")

const yourAction = () => {
    // Add the code here that needs to run twice per second
    btn.removeEventListener("click")
}

btn.addEventListener("click", () => {
    setInterval(yourAction, 500);
});

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

Backbone "recalling" stored data in attributes

Presented here is a basic model: myTestModel = Backbone.Model.extend({ defaults: { title: 'My Title', config: {}, active: 1, } }) While nothing particularly stands out, there is an interesting observation regardi ...

Floating action button within a collapsible panel

I am having trouble placing a fixed-action-btn inside a collapsible body. It keeps appearing in the bottom right corner of the page instead of within the collapsible itself. How can I ensure that the button stays inside the body? Check out this link for r ...

What are the latest advancements in using Java for AJAX technology?

Interested in creating a Rich Internet Application (RIA) with AJAX using Java for the backend. Although DWR may offer an RPC style approach, it hasn't been updated since 2008. Considering alternatives like DOJO and GWT as well. Seeking recommendati ...

The Vanilla JS script in Next.js fails to execute upon deployment

Currently developing a simple static site with Next.js. The lone vanilla JS script in use is for managing a mobile menu - enabling toggling and adding a specific class to disable scrolling on the body: if (process.browser) { document.addEventListener(&ap ...

The Handlebars helper needs to provide a result when a value is present

I have created a Handlebars helper function like this: Here is the code in my JavaScript file: Handlebars.registerHelper('switch', function (sw_val, options) { if (sw_val != '*NONE' && sw_val != false && sw_val != ...

PHP: Exploring the Power of Loop and Conditional Structures

I have encountered an issue with my code that involves adding checkboxes based on data fetched from a database using PHP. I am looking to dynamically add checkboxes with a PHP loop and update a field in the database with JQuery when a checkbox is clicked. ...

Select multiple rows by checking the checkboxes and select a single row by clicking on it in the MUI DataGrid

I am currently utilizing the MUI DataGrid version 4 component. The desired functionalities are as follows: Allow multiple selections from the checkbox in the Data Grid (if the user selects multiple rows using the checkbox). Prevent multiple selections fr ...

I encountered an issue with passing arguments in the invoke function I redesigned

I am currently attempting to replicate the functionality of the .invoke() function. Although I can successfully call the function, I am facing difficulties when it comes to passing arguments. I have made attempts using call and apply, but unfortunately, I ...

The power of ReactJS and the mysterious nature of 'this'

The code below is currently functioning: fetchPost (id) { var mainObject = {}, toReturn = [], promises = []; var that = this; for(var i=id; i<10; i++) { promises.push(axios.get(`api/posts/${i}`)); } axios.all(promises).then(function(resul ...

Internet Explorer 8 is not functioning

Trying to make an Ajax call for API in Sharepoint 2010 but facing limitations in editing the master page. Error: No Transport The code I'm using: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-s ...

Issue with Backbone Event Dropping Functionality

I am facing an issue with my dashboard that has two backbone Views. One of the views consists of various drop zones while the other contains items with draggable="true". Surprisingly, the drop event is not being triggered in these drop zones; however, they ...

Deciphering the intricate mechanics behind _.bind

This block of code is an excerpt from the Underscore library, specifically showcasing the implementation of the _.bind function. However, I am struggling to comprehend the purpose behind modifying the prototype of an empty function. var customConstruc ...

Having trouble getting my Leaflet map to display even after meticulously following the quick-start guide

I am experiencing an issue where the map is not displaying at all, leaving a blank space where it should be. Despite following Leaflet's quick-start guide, I have been unable to determine the cause of this problem. Here is the code that I currently h ...

Eliminating symbols such as $, @, and % from a string using jQuery

Need help with removing special characters like $, @, % from a given string. var str = 'The student have 100% of attendance in @school'; Looking for a way to strip % and $ symbols (or any other special characters) from the above string using jQ ...

Integrating HTML, JavaScript, PHP, and MySQL to enhance website functionality

Exploring the intricacies of HTML, JavaScript, PHP, and MySQL, I have been working on an order form to understand their interactions. View Order Form The aim of this table is to allow users to input a quantity for a product and have JavaScript automatica ...

Tips on implementing nested ajax requests using jquery?

After creating a jQuery code snippet with the following structure: $('button').click(function(event) { }); I included $.post to send data to a PHP file and retrieve table rows. Each row contains an 'add' button. Next, I developed a ...

Executing tasks in a job on GitHub using Node.JS and .NET

I am currently in the process of developing a JavaScript API for a .NET project. In order to streamline my workflow, I would like to know if it is feasible to have GitHub actions set up with both Node.JS and various versions of .NET Core (2.1, 2.2, 3.0 or ...

resetting dropdown selections upon page refresh using jQuery and AJAX

Is there a way to reset or clear the values of two select boxes after refreshing the page in CodeIgniter? Currently, both select boxes retain their values after a refresh. Below is the code I am using: <?php echo form_dropdown('cat_id', $ ...

Updating JSON data in Node.js by adding a new object

I'm facing a situation where I have a JSON file acting as a database to manage users by adding, removing, and modifying them. Currently, I have the following code snippet: 'use strict'; const fs = require('fs'); let student = { ...

Waiting for data to be passed from a parent component within a method

I have a situation where I need to make an API call in my layout and send the received data as an object to my component. The problem arises because the object is empty when the method is called inside the mounted() function. Therefore, I want to execute ...