【问题标题】:Emulate setTimeout with setInterval not working for nested使用 setInterval 模拟 setTimeout 不适用于嵌套
【发布时间】:2015-10-28 08:31:51
【问题描述】:

我为 Chrome 编写扩展程序。当后台页面不活动时,我需要运行延迟任务。由于 setTimeout 在后台选项卡中不起作用,我尝试使用 setInterval 模拟 setTimeout,如下面的代码(位于内容脚本中):

window.timings = [];

function set_timeout(func, time){
  var now = new Date() / 1;
  window.timings.push({
    func: func,
    time: time + now
  });
}

function tick(){
  var now = new Date() / 1;
  window.timings = window.timings.filter(function(delay_obj){
    if (now > delay_obj.time){
      delay_obj.func.call();
      return false;
    } else {
      return true;
    }
  });
}

$(function() {
  setInterval(tick, 1000);
  // some code
});

并且在延迟函数中调用 set_interval 时不起作用:

set_timeout(function(){
  console.log('func1');
}, 2000);

set_timeout(function(){
  console.log('func2');

  set_timeout(function(){
    console.log('func3');
  }, 3000);

}, 3000);

输出:

func1
func2

为什么func3不显示?

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension


    【解决方案1】:

    您显然在 manifest.json 中使用"persistent": false 声明的event page,它在 5 秒不活动后被卸载。链接的文档说要使用chrome.alarms API

    • 如果应将警报设置为大约 5 秒:

      不要使用事件页面,切换到manifest.json中的"persistent": true

    • 如果应该将警报设置为远大于 5 秒的时间:

      manifest.json:

      "permissions": ["alarms"],
      

      后台脚本:

      chrome.alarms.create("MyInterval1", {when: Date.now() + 30*1000});
      
      chrome.alarms.onAlarm.addListener(function(alarm) {
          if (alarm.name == "MyInterval1") {
              console.log("Yay!");
              chrome.alarms.create("MyInterval1", {when: Date.now() + 30*1000});
          }
      });
      

      另请注意:

      如果事件页面关闭,通知和地理定位等其他异步 HTML5 API 将无法完成。相反,请使用等效的扩展 API,例如通知。

      如果您的扩展程序使用 extension.getBackgroundPage,请改用 runtime.getBackgroundPage。较新的方法是异步的,因此它可以在必要时在返回之前启动事件页面。

    【讨论】:

    • 感谢您的回答!但最终,我决定在从 setInterval 函数调用的 background.js 中使用 chrome.tabs.sendMessage,在内容脚本中使用 chrome.runtime.onMessage.addListener
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多