2016-12-28 51 views
0

如何在另一功能中停止功能?如何在另一功能中停止功能

例如:

var \t snow = function(){ 
 
    var interval = setInterval(function(){ 
 
    alert('letItSnow') 
 
    }, 1000); 
 
}; 
 
snow();

clearInterval(snow.interval) - 异常

+0

你'clearInterval'因为在函数中的变量不是函数对象的属性抛出异常。 – doug65536

回答

2

在JavaScript中,访问范围通过函数声明有限的,所以你的本地声明的变量不会被外界访问,因此你必须返回,或将其设置为一个全局变量(父范围变量可用)

你需要做小幅调整,以你的函数,像这样做:

var snow = function(){ 
      return setInterval(function(){ 
       alert('letItSnow'); 
      }, 1000); 

     }; 

    var interval = snow(); 
    //on some event -- clearInterval(interval) 

可以阿尔斯Ø使setTimeout和返回ID属性的function这将适用于所有的情况下的即

var snowClass = function(){ 
    this.init = function(msg){ 
     this.interval = setInterval(function(){alert(msg)},1000); 
    } 

} 
var snowObj = new snowClass(); 
snowObj.init('Let it snow'); 
//on some event -- clearInterval(snowObj.interval) 
0

试试这个在您的代码

var timeout1 = {}; 
 
var timeout2 = {}; 
 

 
function function1(){ 
 
//codes 
 
    if(timeout2){ 
 
     clearTimeout(timeout2); 
 
    } 
 
    timeout1 = setTimeout("function1()",5000); 
 
}  
 

 
function function2(){ 
 
//codes 
 
    if(timeout1){ 
 
     clearTimeout(timeout1); 
 
    } 
 
    timeout2 = setTimeout("function2()",5000); 
 
}

1

你指的是snow.interval,它假设是snow对象的属性。但在你的代码interval只是局部变量。相反,你可能要在全球范围内定义interval所以这将是全球访问http://www.w3schools.com/js/js_scope.asp

var interval, snow = function(){ 
    interval = setInterval(function(){ 
    console.log('letItSnow') 
    }, 1000); 
}; 
snow(); 
clearInterval(interval); 
1

如果我理解正确的问题,你要停止snow功能之外的时间间隔。

您可以在snow函数之外声明interval变量,以便在snow函数之外使用它(以清除间隔)。

var interval; 
 
var snow = function(){ 
 
    interval = setInterval(
 
     function(){ 
 
      alert('letItSnow') 
 
     }, 
 
     1000 
 
    ); 
 
}; 
 
snow(); 
 
clearInterval(interval);