您必须将引用放在处理程序timout
的公共范围内click
,如下所示。当var
在新作用域中使用时,变量会在局部作用域[1]中再次声明。
var int = setInterval(back, autoTimerTime);
var timeout; // This variable is now shared by all $('.arrow-down').click funcs
//down arrow
$('.arrow-down').click(function(){
if (!$('ul.as-thumbs').is(':animated')) {
back();
clearInterval(int);
clearTimeout(timeout);
timeout = setTimeout(function() {
// Removed `var` too
int = setInterval(back, autoTimerTime);
}, 8000);
}
});
[1]:局部/全局变量的图解说明
简而言之,以var
关键字为前缀的变量在本地范围内再次声明。在 JavaScript 中,可以通过用 . 包围块来创建新范围function() { .. }
。
当请求一个变量时,引擎首先在当前(本地)范围内查找。如果变量存在,则使用该变量。
否则,将检查父范围,等等,直到找到变量。如果在顶部(全局范围)找不到变量,则会发生以下情况:
- 在严格模式下,
ReferenceError
将抛出 a。
- 分配时
foo = 1
,变量将在全局范围内声明
@Nitpicks:let
不考虑)
- 阅读时: A
ReferenceError
将被抛出。
var int = 1, timeout = 2, homeless = 3;
function click() {
var timeout = 1;
homeless = 4;
timeout = function() {
var int = 2;
}
}
click();
Variables in the global scope:
- int (declared using var, inititalized at 1)
- timeout (declared using var, inititalized at 2)
- homeless(declared using var, initialized at 3)
--- New scope of: function click()
- No declaratation of `int`, so if used, `int` refers to the global `int`
- Global var: homeless (assigned 4)
- Local var: timeout (declared using var, init at 1)
- Local var: timeout (assigned anonymou function())
--- New scope of: function()
- Local var: int (declared using var, init at 1)
- Accessible vars from parent scope: timeout
- Accessible vars from global scope: homeless, int
(Note that the global `timeout` var is unreachable, because it
has been redeclared at the parent scope)