为什么我不能在下面的示例中使用 clearInterval?

Why I can not clearInterval in the following example?

我有以下问题。当 timer_mou 开始计数时,当 pause 等于 closeit 时,它不会清除间隔。

我在这里错过了什么?

function my_timer(pause){
    console.log('function: '+pause);

    var timer_mou = setInterval(function() { 
        console.log('counting');
    }, 5000);  

    if (pause == 'closeit') { 
        clearInterval(timer_mou); 
    }     
}

只需将 setInterval 放在暂停函数之外,在全局范围内定义变量 timer_mou,然后当您调用您的函数时,它会正确清除它,而不是在每个函数上都定义它调用函数,检查下面的工作示例。

希望对您有所帮助。

var i = 0;
var timer;

start();

$('#pause').on('click',function(){
  pause()
})

$('#restart').on('click',function(){
  restart()
})

function pause(){
  clearInterval(timer);  
}

function restart(){
  i=0;
  pause()
  start();
}

function start(){
  timer = setInterval(function() { 
    i++;
    console.log('Counting '+i);
  },1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='pause'>Pause</button>
<button id='restart'>Restart</button>

您需要在函数外定义 timer_mou。在您的情况下,您将无法清除计时器,因为您丢失了对计时器的引用并且在每次函数调用时都创建了一个新的计时器实例。

试试这样的:

var timer_mou;

function start_timer() {
  timer_mou = setInterval(function() { 
    console.log('counting');
  }, 5000);
}

function stop_timer() {
  clearInterval(timer_mou);
}

这是一个非常烦人的问题,与 scope 有关。当您在函数内部声明 setInterval 时,唯一可以清除它的地方是在函数的迭代内部。所以,

my_timer("") //Starts a timer in the function
my_timer("closeit") //Starts a timer in the function, then stops it 
//with the other timer running in the background

您可以将问题归结为您的间隔被多次声明,并且您只能在函数内部停止它。所以,如果你想让 my_timer 函数启动定时器,但是如果给它参数 "pauseit" 就停止,你可以这样实现:

function my_timer(pause){
    console.log('function: '+pause);

    if(typeof timer_mou === "undefined"){ //If the interval already exists, don't start a new one
            timer_mou = //Defines in global scope
            setInterval(function() { 
               console.log('counting');
        }, 5000);  
    }
    if (pause == 'closeit') { 
        clearInterval(timer_mou); 
    }     
}

因此,在您的函数的新版本中,它会检查间隔是否已定义,如果没有,则在 全局范围 中定义它,以便您稍后可以将其删除。

在手机上完成,所以这是我对错误格式和拼写错误的借口。