De acordo com o StackOverflow, há dois tipos de loop baseado em tempo: o setInterval e o setTimeout.
Ambos podem ser chamados a qualquer momento do código, e retornam um inteiro com o ID do agendamento da função. Entre os dois, a melhor opção é utilizar o setTimeout e, no final, adicionar outro timeout para chamar novamente a mesma função (recursividade).
É importante pegar o ID resultado porque, se for preciso, os eventos clearInterval e clearTimeout podem ser chamados para abortar a função agendada. Ambos tem um único parâmetro: o ID obtido.
Na íntegra, o post do StackOverflow:
Note that
setTimeout
andsetInterval
are very different functions:
setTimeout
will execute the code once, after the timeout.setInterval
will execute the code forever, in intervals of the provided timeout.Both functions return a timer ID which you can use to abort the timeout. All you have to do is store that value in a variable and use it as argument to
clearTimeout(tid)
orclearInterval(tid)
respectively.So, depending on what you want to do, you have two valid choices:
// set timeout var tid = setTimeout(mycode, 2000); function mycode() { // do some stuff... tid = setTimeout(mycode, 2000); // repeat myself } function abortTimer() { // to be called when you want to stop the timer clearTimeout(tid); }
or
// set interval var tid = setInterval(mycode, 2000); function mycode() { // do some stuff... // no need to recall the function (it's an interval, it'll loop forever) } function abortTimer() { // to be called when you want to stop the timer clearInterval(tid); }
Both are very common ways of achieving the same.
** Atualizado em 22 de maio de 2015!
Outra forma de utilizar um loop é com a função .each(), disponível no jQuery, conforme o link: http://www.sitepoint.com/jquery-each-examples/
Link original [ stackoverflow.com/questions/2133166/loop-timer-in-javascript ]