简体   繁体   English

如何在一定间隔内重新执行功能?

[英]How to re-execute a function in a certain interval?

I'm developing a Chrome extension and it needs to run a function in a fixed period of time so it can work with dynamic pages. 我正在开发Chrome扩展程序,它需要在固定的时间段内运行某个功能,以便它可以处理动态页面。

I have used setInterval but it only executed the function once, and if it were modified to the following: 我使用过setInterval但是它只执行一次功能,并且如果将其修改为以下内容:

function sumfunc(){
    document.body.innerHTML = dosumthin(document.body.innerHTML,false);
    setInterval(sumfunc(),1000);
}

It would lag the page while filling the call stack and making it seem like the page never finishes loading. 在填充调用堆栈时,它会滞后页面,使页面看起来似乎永远无法完成加载。

Remove () : 删除()

setTimeout(sumfunc,1000);

setTimeout() 's first argument takes a function definition, not an execution of one. setTimeout()的第一个参数采用函数定义,而不是函数定义。

As your executing sumfunc inside sumfunc , this will cause immediate infinite recursion, which will potentially cause a stack overflow, as you have described. 如您所sumfunc sumfunc ,在sumfunc执行sumfunc ,这将导致立即无限递归,这有可能导致堆栈溢出。


Therefore replace your code with the following: 因此,将代码替换为以下内容:

function sumfunc(){
    document.body.innerHTML = dosumthin(document.body.innerHTML,false);
    setTimeout(sumfunc,1000);
}

Just use setInterval instead: 只需使用setInterval

function sumfunc(){
 document.body.innerHTML = dosumthin(document.body.innerHTML,false);
}
window.setInterval(sumfunc,1000);

The page lags because every time the timout starts it will call the timeout again. 该页面滞后是因为每次启动timout都会再次调用超时。 You have to set the timeout outside of the function like this: 您必须像这样在函数外部设置超时:

setInterval(sumfunc,1000);
function sumfunc(){
    document.body.innerHTML = dosumthin(document.body.innerHTML,false);
}

You need an interval rather than a timeout. 您需要一个时间间隔而不是超时。

function sumfunc(){
    document.body.innerHTML = dosumthin(document.body.innerHTML,false);
}

setInterval(sumfunc, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM