简体   繁体   中英

Stop jquery event

I want if I call my second if else work then first one should stop. But that also keep running. If first one running second should stop.

if(e.keyCode == 39) {
  setInterval(function(){
  //

  }, 10);
} else if(e.keyCode == 37) {
  setInterval(function(){

  //    
  }, 10);
}

setInterval() returns the ID of the set timer, that can be used to stop it.

Something like this should work:

var intervalId1, intervalId2;

if(e.keyCode == 39) {
    intervalId1 = setInterval(function() { ... }, 10);
    if (intervalId2) {
        clearInterval(intervalId2);
    }
} else if(e.keyCode == 39) {
    intervalId2 = setInterval(function() { ... }, 10);
    if (intervalId1) {
        clearInterval(intervalId1);
    }
}

You need to use a variable which is in a shared scope

//in a shared scope, probably outside teh function where this code is placed
var interval;

if (e.keyCode == 39) {
    if (interval) {
        clearInterval(interval);
    }
    interval = setInterval(function () {
        //
        interval = undefined;
    }, 10);
} else if (e.keyCode == 37) {
    if (interval) {
        clearInterval(interval);
    }
    interval = setInterval(function () {
        //

        interval = undefined;
    }, 10);
}

setInterval returns a handle which you can use to stop/clear the interval.

It is also important that you store this handle outside the function itself, or else it will be cleared next time the function runs.

Since you only care about one interval to run, you also only need to store one handle.

//define globally outside your function
var interval = null;

//your function starts here

interval && clearInterval(interval); // (same as if(interval){clearInterval(interval);})

if(e.keyCode == 39) {
    interval = setInterval(function(){    
       //    
    }, 10);
} else if(e.keyCode == 37) {
    interval = setInterval(function(){    
      //    
    }, 10);
}

Using one variable interval to store the return id of setInterval and whenever call to function clear that interval you will get what you need.

   var interval;
    $("#text_box").keydown(function(e){
        e.preventDefault();
        if(e.keyCode == 39){
            clearInterval(interval);
            interval=setInterval(sample1,1000);
        }
        else if(e.keyCode == 37){
            clearInterval(interval);
            interval=setInterval(sample2,1000);
        }
    });
    function sample1(){
        console.log("1");
    }
    function sample2(){
        console.log("2");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM