简体   繁体   English

如何停止执行一次javascript函数(轮询)?

[英]How can I stop a javascript function (poll) from being executed multiple times?

I have a poll() function: 我有一个poll()函数:

$("document").ready(function(){
   poll(10);
   $("#refresh").click(function(){ poll(10); });
});

function poll(timeout){
   return setTimeout(function(){
      if (timeout == 10){
         timeout = 10000;
      }
      $.ajax({ url: "/ajax/livedata.php", success: function(data){
         $("#result").html(data);
         poll(timeout);
      }, dataType: "json"});
   }, timeout);
}

So, what happens there: 因此,那里发生了什么:

1) on page load, poll() is called and the loop starts being executed. 1)在页面加载时,调用poll()并开始执行循环。

2) on #refresh click, poll() is called right at that moment to request new data immediately. 2)在#refresh单击上,此时将立即调用poll()以立即请求新数据。

The problem: whenever I click #refresh to request new data, the poll() is called again, but fired multiple times (first time the initial + every new click). 问题是:每当我单击#refresh来请求新数据时,都会再次调用poll() ,但是会触发多次(第一次是首次+每次新点击)。 Thus it fires not every 10 seconds as expected, but multiple times every 10 seconds (depending on how many times I clicked on #refresh ). 因此,它不是每10秒触发一次,而是每10秒触发一次(取决于我点击#refresh )。

How can I fix this, so that whenever I click #refresh , only 1 instance will be left looping? 如何解决此问题,以便每当我单击#refresh ,仅剩下1个实例将循环播放?

first store your setTimeout Object to a variable somewhat like this 首先将您的setTimeout对象存储到这样的变量中

var a = poll(10);

then stop it upon clicking refresh by using this code 然后使用此代码在单击刷新时将其停止

clearTimeout(a);

So it will be like this 所以会像这样

$("document").ready(function(){
   var a = null;   
   $("#refresh").click(function(){ 
      if(a != null){
           clearTimeout(a);
           a = null;
      }
      a = poll(10); 
   });
});

reference: 参考:

http://www.w3schools.com/jsref/met_win_cleartimeout.asp http://www.w3schools.com/jsref/met_win_cleartimeout.asp

http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_stop http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_stop

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

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