Search code examples
ajaxlong-polling

Ajax long polling how to detect if it's currently running


We are using a polling function, but there are 4 places where we have to make sure that polling is running. How can we determine if a current polling instance is running, so as we don't create another one, and have overlapping polling going?

  function longPoll(){
      // do the request
      chrome.storage.local.get("userAuth", function(data) {
        if(data.hasOwnProperty('userAuth')){
          if(!localStorage.disableNotifications){
            checkUnread();
          }
        }


      });
      setTimeout(function(){ 
        longPoll();
        console.log('polling: '+new Date().getTime());
      }, 5000);
    };

Solution

  • You can set up a boolean var to track if your polling is currently running. Something like this for example:

    var polling = false;
    
    function longPoll(){
    
      //do nothing if already polling
      if( polling )
      {
        return;
      }
    
      //set polling to true
      polling = true;
    
      //rest of function code goes here...
    
      //set polling to false after process is finished
      polling = false;
    
      setTimeout(function(){ 
        longPoll();
        console.log('polling: '+new Date().getTime());
      }, 5000);
    };