使用setInterval模拟setTimeout不适用于嵌套

使用setInterval模拟setTimeout不适用于嵌套

本文介绍了使用setInterval模拟setTimeout不适用于嵌套的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  code> not displayed?

解决方案

您显然使用 runtime.getBackgroundPage 来代替。新的方法是异步的,因此它可以在返回之前根据需要启动事件页面。




I write extension for Chrome. And I need run delayed tasks when background page inactive. Cause setTimeout not working in background tabs, I try emulate setTimeout with setInterval, like code below (located in content script):

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
});

And it don't work when set_interval call in delay function:

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

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

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

}, 3000);

Output:

func1
func2

Why func3 not displayed?

解决方案

You're apparently using an event page declared with "persistent": false in manifest.json, it is unloaded after 5 seconds of inactivity. The linked documentation says to use chrome.alarms API.

  • In case the alarm should be set for a period around 5 seconds:

    Don't use the event page, switch to "persistent": true in manifest.json.

  • In case the alarm should be set for a period much larger than 5 seconds:

    manifest.json:

    "permissions": ["alarms"],
    

    background script:

    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});
        }
    });
    

    Also note:

这篇关于使用setInterval模拟setTimeout不适用于嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:01