setInterval does not repeat

Asked

Viewed 97 times

7

I’m trying to solve the following problem:

On my page, the setInterval does not repeat, I tried several ways, until simplify in the mode below to see if it would work, but even so it does not repeat, is working as a setTimeout.

function teste(){
    $("#teste").append("a");
 }
 var x = setInterval(teste(),1000);

1 answer

8

The problem is that you are passing the function result teste to the setInterval.

setInterval(teste(), 1000);
// 'teste' é executado, e, como ele não retorna nada, essa linha é equivalente a:
setInterval(undefined, 1000);

Finally, to tidy up, pass the reference to the function teste to the setInterval. Tidy code:

function teste(){
    $("#teste").append("a");
}
var x = setInterval(teste, 1000); // <-- sem parênteses

Jsfiddle

  • Thank you for the reply.

  • is it worth noting? http://jsfiddle.net/qj57Lffz/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.