简体   繁体   中英

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

I have a poll() function:

$("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.

2) on #refresh click, poll() is called right at that moment to request new data immediately.

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). Thus it fires not every 10 seconds as expected, but multiple times every 10 seconds (depending on how many times I clicked on #refresh ).

How can I fix this, so that whenever I click #refresh , only 1 instance will be left looping?

first store your setTimeout Object to a variable somewhat like this

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/js/tryit.asp?filename=tryjs_timing_stop

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