Javascript setInterval 在 Google Chrome 扩展程序中不起作用(仅触发一次)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8971871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:16:06  来源:igfitidea点击:

setInterval not working (firing only once) in Google Chrome extension

javascriptgoogle-chromeasynchronousgoogle-chrome-extensionsetinterval

提问by Camilo Martin

Just as the title says: setIntervalis only firing its callback once.

正如标题所说:setInterval只触发一次回调。

manifest.json:

清单.json:

{
    //...
    "content_scripts" : [{
        "js" : ["code.js"],
        //...
    }],
    //...
}

code.js (example):

code.js(示例):

setInterval(alert('only shown once'),2000);

Why, and how I could fix it? The code works well outside of an extension (even in a bookmarklet).

为什么,我该如何解决?该代码在扩展程序之外运行良好(即使在书签中)。

回答by qwertymk

setInterval(function() { alert('only shown once') },2000);

You need to pass a function reference like alertand not a return value alert()

您需要传递一个函数引用alert而不是返回值alert()

回答by Quentin

setIntervalisn't working at all.

setInterval根本不工作。

The first argument should be a function, you are passing it the return value of alert()which isn't a function.

第一个参数应该是一个函数,你传递给它的alert()不是函数的返回值。

Use the three argument version:

使用三个参数版本:

setInterval(function,time,array_of_arguments_to_call_function_with);
setInterval(alert,2000,['only shown once']);

回答by Dario

The way you wrote it it's wrong:

你写的方式是错误的:

setInterval()wants a function and a numerical value: setInterval(function(){//your code}, timeInterval).

setInterval()想要一个函数和一个数值:setInterval(function(){//your code}, timeInterval)