开发者

Using setInterval/clearInterval effectively

I am adding new features to my already developed application. I am trying to add an auto rendering functionality which automatically render some part of the screen after a certain time interval. I am using setInterval for this, everything is working fine.

My question is, how should I call the clearInterval(intervalId) function for all other events except one. Please consider an example: Suppose I have some events related to current screen, and I want to start my setInterval only on ".myBtn" click and stop for all other events.

    var intervalId = 0;

    $(".myBtn").click(function(){
        intervalId = setInterval(function(){
          alert("execute something");
        }, 2000);  
    });

   $(".otherElm").click(function(){
      // some other stuff.
   });


   $(".otherElm1").click(function(){
      // some other stuff.
   });


   $(".otherElm2").click(function(){
      // some other stuff.
   });

For the above situation, I know only one way to stop the interval i.e. to put "clearInterval(intervalId)" in eve开发者_运维知识库ry other event.

But, is there any other way to do this?

Hope I have put everything so that one can understand my question.

Thanks in advance


You are right in your comment - you have to put clearInterval(IntervalId) into all of the events that you require to stop the event. Is there a problem with doing this?

Edit:

Identify them all with a class - say elm. Once this is done, use $(".elm").click(clearinterval).


Another way to do it would be to do something like:

$(".myBtn").click(function(){
    setTimeout(someFunction,2000);  
});

var someFunction = function()
{
    // CODE HERE
    if(conditions for stopping function are not met){
        //Run function again
        setTimeout(someFunction, 2000);
    }
}

Although more code, I find it easier to manage, especially if you end up having a lot of intervalIDs to deal with.


setInterval("alert('negaweblog.wordpress.com')",1000);

1000 - 1 secs.

Every one second, it will alert 'negaweblog.wordpress.com'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜