简体   繁体   中英

Call onClick function in setInterval

I have an onClick function which works as expected. Once this function has been triggered once by click, I want to run it periodically using setInterval .

Here is how I have modified the code to attempt this:

    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 have modified the calling of the function from setInterval according to one to one of the answers here .

I think the problem here is with passing the parameters to the function. Is there a way of achieving this?

The problem was that with creating the interval in the function itself, made an infinite growing interval call and may be that's why it did not work. The work around can be something like this:

You define a function and call it using the setTimeout from onClick:

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

   // Add this in your onClick function to call the following function that creates the interval
   setTimeout( function() { startInterval(clickData); }, 1);
}

Now, in the startInerval function, you can call onClick; however to prevent to accumulate the intervals, I declare a flag to check and create the interval only once:

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

You can use add a click listener, then remove the click listener after the button is pressed and the interval is set:

const buttonID = document.getElementById("INSERT-ID-OF-YOUR-BUTTON-HERE")

const yourFunction = () => {
    // your code that you want to be called twice per second goes here
    buttonID.removeEventListener("click")
}

buttonID.addEventListener("click", () => {
    setInterval(yourFunction, 500);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM