What is "setinterval"
The setInterval
(unlike the settimeout) is a method that creates an infinite timer that will execute a code every specified period (in milliseconds). This method generates a loop in itself.
Basic syntax:
setInterval(código a ser executado, intervalo em milissegundos)
Example:
// irá chamar a função minhaFuncao a cada 5 segundos
// 1000 milissegundos = 1 segundo
setInterval(minhaFuncao, 5000);
As the timer is continuous and uninterrupted (infinite), to cancel it you need to assign an identification and use clearInterval(identificação)
when you want to stop the timer:
var meuIntervalo = setInterval(minhaFuncao, 5000);
clearInterval(meuIntervalo);
It is also possible to run a code block within the method itself, using function(){}
in the first parameter:
var meuIntervalo = setInterval(function(){
// código
}, 5000);
The result is the same as in the first example, differing by the fact that, while it calls an external function, it executes one within itself. The use of both forms will depend on the application.
- Documentation on the MDNIn English