Javascript 停止jquery事件

Javascript 停止jquery事件,javascript,jquery,Javascript,Jquery,我想如果我打电话给我的第二个,如果还有工作,那么第一个应该停止。但这也在继续。如果第一个运行第二个应该停止 if(e.keyCode == 39) { setInterval(function(){ // }, 10); } else if(e.keyCode == 37) { setInterval(function(){ // }, 10); } setInterval返回可用于停止设置计时器的设置计时器的ID 像这样的方法应该会奏效: var inte

我想如果我打电话给我的第二个,如果还有工作,那么第一个应该停止。但这也在继续。如果第一个运行第二个应该停止

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

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

  //    
  }, 10);
}

setInterval返回可用于停止设置计时器的设置计时器的ID

像这样的方法应该会奏效:

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);
    }
}

您需要使用共享作用域中的变量

//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返回一个句柄,您可以使用该句柄停止/清除间隔

将此句柄存储在函数本身之外也很重要,否则下次函数运行时它将被清除

因为您只关心一个运行间隔,所以您也只需要存储一个句柄

//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);
}
使用一个变量interval来存储setInterval的返回id,每当调用函数清除该间隔时,您将得到所需的内容

   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");
    }
看看这个例子