Is there a way to check if a var is using setInterval()?

前端 未结 6 888
失恋的感觉
失恋的感觉 2020-12-12 16:30

For instance, I am setting an interval like

timer = setInterval(fncName, 1000);

and if i go and do

clearInterval(timer);
         


        
6条回答
  •  春和景丽
    2020-12-12 16:51

    You COULD override the setInterval method and add the capability to keep track of your intervals. Here is an untestet example to outline the idea. It will work on the current window only (if you have multiple, you could change this with the help of the prototype object) and this will only work if you override the functions BEFORE any functions that you care of keeping track about are registered:

    var oldSetInterval = window.setInterval;
    var oldClearInterval = window.clearInterval;
    window.setInterval = function(func, time)
    {
      var id = oldSetInterval(func, time);
      window.intervals.push(id);
      return id;
    }
    window.intervals = [];
    window.clearInterval = function(id)
    {
      for(int i = 0; i < window.setInterval.intervals; ++i)
        if (window.setInterval.intervals[i] == id)
        {
          window.setInterval.intervals.splice(i, 1);
        }
      oldClearInterval(id);
    }
    window.isIntervalRegistered(id)
    {
      for(int i = 0; i < window.setInterval.intervals; ++i)
        if (window.setInterval.intervals[i] == func)
          return true;
      return false;
    }
    
    
    
    var i = 0;
    var refreshLoop = setInterval(function(){
        i++;
    }, 250);
    
    if (isIntervalRegistered(refrshLoop)) alert('still registered');
    else alert('not registered');
    clearInterval(refreshLoop);
    if (isIntervalRegistered(refrshLoop)) alert('still registered');
    else alert('not registered');
    

提交回复
热议问题