setInterval - restablecimiento de JavaScript

I am using setInterval in a loop. Once the condition has been met (aa=bb) and interval cleared, is it possible to reset interval?

var interval = setInterval(function() 
{                                       
   if( aa == bb) 
   {
     clearInterval(interval);                   
   }
} , 10000);

preguntado el 01 de febrero de 12 a las 01:02

Could you please show a bit more of your code? What do you mean "in a loop"? Calling setInterval from within a loop creates multiple intervals that run simultaneously (and 95% of the time when I've seen this done it was due to a misunderstanding about how it works). What do you mean by "reset interval"? -

1 Respuestas

If you make the code a function like this, you can call it anytime to start it over.

function startInterval() {
   var interval = setInterval(function() {                                       
       if( aa == bb) {
         clearInterval(interval);                   
       }
    }, 10000);
}

startInterval();

Respondido 01 Feb 12, 05:02

aa and bb were in local scope. can I pass them in? - Mustapha George

@MustaphaGeorge - You can define startInterval in that same scope and it will automatically have access to aa y bb. If you pass them in, then they may end up separate copies that won't change when you expect them to. - jfriend00

thanks, I did that, but my code seems to be blasting through the startInterval function. can there be compatibility with jQuery? - Mustapha George

@MustaphaGeorge - you'd have to show us more of your code for us to know why it isn't working properly. The startInterval() function will execute and finish immediately. It just starts the interval timer which proceeds on it's own. - jfriend00

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.