简体   繁体   English

在setInterval中调用onClick function

[英]Call onClick function in setInterval

I have an onClick function which works as expected.我有一个按预期工作的onClick function。 Once this function has been triggered once by click, I want to run it periodically using setInterval .通过单击触发此 function 一次后,我想使用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 .我已经根据此处的一对一答案修改了setInterval中 function 的调用。

I think the problem here is with passing the parameters to the function. Is there a way of achieving this?我认为这里的问题是将参数传递给 function。有没有办法实现这个?

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.问题是在 function 本身中创建间隔时,进行了无限增长的间隔调用,这可能就是它不起作用的原因。 The work around can be something like this:解决方法可能是这样的:

You define a function and call it using the setTimeout from onClick:您定义一个 function 并使用来自 onClick 的 setTimeout 调用它:

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;现在,在startInerval function,可以调用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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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