GGG
GGG

Reputation: 670

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.

I have used setInterval but it only executed the function once, and if it were modified to the following:

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.

Upvotes: 0

Views: 204

Answers (4)

Andreas Furster
Andreas Furster

Reputation: 1638

The page lags because every time the timout starts it will call the timeout again. 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);
}

Upvotes: 0

Simon Brahan
Simon Brahan

Reputation: 2076

You need an interval rather than a timeout.

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

setInterval(sumfunc, 1000);

Upvotes: 0

ladar
ladar

Reputation: 5876

Just use setInterval instead:

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

Upvotes: 1

Curtis
Curtis

Reputation: 103348

Remove ():

setTimeout(sumfunc,1000);

setTimeout()'s first argument takes a function definition, not an execution of one.

As your executing sumfunc inside sumfunc, this will cause immediate infinite recursion, which will potentially cause a stack overflow, as you have described.


Therefore replace your code with the following:

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

Upvotes: 2

Related Questions