通过另一个函数调用时,clearTimeout()不起作用

ann*_*ani 0 javascript

什么时候clearTimeout(fun); 添加到setTimeout函数下面它应该工作,但我不能遇到这个代码的错误.

<!DOCTYPE html>
<html>
   <body>
    <button onclick="myFunction()">Try it</button>
    <button onclick="myfunction()">click me</button>
    <script> 
       function myFunction() {
          var fun = setTimeout(function(){ alert("Hello"); }, 3000);
       }
       function myfunction(){
          clearTimeout(fun); 
       } 
   </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Fur*_*usD 7

fun因为变量在第二个范围内是不可访问的,myFunction因为它是第一个变量的局部变量myFunction.fun需要在全局声明 - 或在两个函数的父级别声明.

<script>
  var fun;
  function create() {
    fun = setTimeout(function(){ alert("Hello"); }, 3000);
  }
  function cancel(){
    clearTimeout(fun); 
  }
</script>
Run Code Online (Sandbox Code Playgroud)

作为旁注,函数需要具有唯一的名称,否则第二个声明将覆盖第一个.


Ous*_* D. 5

这是因为所述标识符fun唯一的包含代码块中存在.

解决方案是您需要在函数之外声明它,这将使您能够fun在两个函数中使用标识符.

此外,即使您的函数标识符由第一个区分'f',但最好为它们提供有意义的标识符,这些标识符可以通过眼睛轻松区分.

<!DOCTYPE html>
<html>
   <body>
<button onclick="start()">Try it</button>
<button onclick="end()">click me</button>
<script> 
   var fun;
   function start() {
      fun = setTimeout(function(){ alert("Hello"); }, 3000);
   }
   function end(){
      clearTimeout(fun); 
   } 
   </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)