setInterval does not repeat

7

I'm trying to solve the following problem:

On my page, setInterval does not repeat, tried in many ways, even simplified in the mode below to see if it would work, but it still does not repeat, it is working as a setTimeout .

function teste(){
    $("#teste").append("a");
 }
 var x = setInterval(teste(),1000);
    
asked by anonymous 03.06.2015 / 14:34

1 answer

8

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

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

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

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

JSFiddle

    
03.06.2015 / 14:43