用户离开标签时暂停的setInterval()?

时间:2015-03-04 18:36:29

标签: javascript

javascript中是否有任何类似setInterval()的方法,当用户离开标签时会停止并在用户再次进入标签时恢复?

1 个答案:

答案 0 :(得分:1)

您可以使用Visibility API创建自己的API,以检测标签何时变为可见或隐藏,并调用本机setIntervalclearInterval

var mySetInterval, myClearInterval;
(function() {
  var data = Object.create(null),
      id = 0;
  mySetInterval = function mySetInterval(func, time) {
    data[id] = {
      nativeID: setInterval(func, time),
      func: func,
      time: time
    };
    return id++;
  };
  myClearInterval = function myClearInterval(id) {
    if(data[id]) {
      clearInterval(data[id].nativeID);
      delete data[id];
    }
  };
  document.addEventListener('visibilitychange', function() {
    if(document.visibilityState == 'visible')
      for(var id in data)
        data[id].nativeID = setInterval(data[id].func, data[id].time);
    else
      for(var id in data)
        clearInterval(data[id].nativeID);
  });
})();



var mySetInterval, myClearInterval;
(function() {
  var data = Object.create(null),
      id = 0;
  mySetInterval = function mySetInterval(func, time) {
    data[id] = {
      nativeID: setInterval(func, time),
      func: func,
      time: time
    };
    return id++;
  };
  myClearInterval = function myClearInterval(id) {
    if(data[id]) {
      clearInterval(data[id].nativeID);
      delete data[id];
    }
  };
  document.addEventListener('visibilitychange', function() {
    if(document.visibilityState == 'visible')
      for(var id in data)
        data[id].nativeID = setInterval(data[id].func, data[id].time);
    else
      for(var id in data)
        clearInterval(data[id].nativeID);
  });
})();

var log = document.getElementById('log'),
    timer;
document.getElementById('start').onclick = function() {
  var num = 0;
  myClearInterval(timer);
  timer = mySetInterval(function(){
    log.innerHTML = num++;
  }, 1e3);
};

<input id="start" type="button" value="Start" />
<span id="log"></span>
&#13;
&#13;
&#13;

请注意,上述API不应与原生API混合使用,例如:不要尝试使用mySetInterval创建并使用clearInterval清除。因此,mySetInterval返回的ID故意与本地ID不同。