0

我创建了一个滑块,它与下一个/上一个箭头一起在计时器上工作。

单击箭头时,我想停止自动计时器,然后在最后一次单击后重新启动 x-time。不幸的是,我目前似乎对计时器进行了查询,因此如果多次单击箭头,自动计时器将重新启动,但移动速度非常快......

我似乎无法解决 - 如何只维护一个 setInterval 并避免它们堆积......

非常感谢任何帮助-粘贴在下面的代码

    var int = setInterval(back, autoTimerTime);
    //down arrow    
    $('.arrow-down').click(function(){
        if (!$('ul.as-thumbs').is(':animated')) {
            back();
            clearInterval(int);
            clearTimeout(timeout);
            var timeout = setTimeout(function() {
                var int = setInterval(back, autoTimerTime);
            }, 8000);
        }
    });
4

2 回答 2

1

您必须将引用放在处理程序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不考虑)
  • 阅读时: AReferenceError将被抛出。
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)
于 2012-01-12T18:58:28.660 回答
0

clearTimeout(timeout);永远不会起作用,因为“超时”不是全局变量。您在函数内定义它。

于 2012-01-12T19:00:14.163 回答