Stopping timeout started from an object instance when all references are lost
I made a polling system for which you must use instantiation, thus allowing you to have multiple pollers going at the same time.
The polling uses setTimeout to delay each request according to a defined poll rate.
Here is a very simplified version:
function Poller(url, rate, callback) {
开发者_如何学运维  var timeoutReference = null;
  var public = {
    poll: function() {
      /* Request here i.e. $.GET(....)
         calling callback with recieved data on success */
      console.log("Poller running");
      timeoutReference = setTimeout(public.poll, rate);                
    },
    stop: function() { 
      clearTimeout(timeoutReference); 
    }
  }
  return public;    
}
var poller1 = new Poller('http://www.site.com/feed', 5000, readData);
poller1.poll();
Now if I do
poller1 = null;
The timeout is still running and will run forever. I need to do
poller1.stop(); 
poller1 = null;
for it to work as intended.
Is there any way to clear the timeout when all references are lost, thus omitting the need for calling poller1.stop(); before unreferencing the instance?
There's no way to "find" a lost timer index (they're just numbers). You could always wrap "setTimeout()" in a function that keeps a global registry or something. You'd still have the problem of having to identify them somehow, but there are several ways to approach that.
 加载中,请稍侯......
      
精彩评论