2011-05-26 63 views
-1

可能重复:
How to pause a setTimeout call ?使用Javascript - 停止重复功能

我有一个被调用的页面加载函数开头的重复功能:

 setTimeout(function() { 
      repeat(); 
     }, 8000) 

这个函数每8秒调用一次repeat(),这个函数里面有一个aja x更新页面上的计数器。点击计数器给用户一个包含许多消息的下拉菜单。计数器值等于用户拥有的消息数量。有点像Facebook通知。

当点击使用jQuery隐藏和显示其下拉菜单中林:

$('#messages').click(function() { 
     $('#messagesDropDown').slideDown(); 
    }) 
    .mouseleave(function() { 
     $('#messagesDropDown').slideUp(); 
    }); 

#messagesDropDown可见我想停止repeat()功能,以防止更新的邮件列表,而林观看目前的。

On .mouseleave我想再次启动repeat()函数。

任何人有任何想法我可以'停止'重复功能在.click功能,并再次启动.mouseleave

+2

的setInterval()重复序列没有的setTimeout() – Ibu 2011-05-26 07:22:17

+0

看这里:http://stackoverflow.com/questions/2626005/how-to-pause-a-settimeout-call – Krimo 2011-05-26 07:21:41

回答

1

你说这个代码开始重复功能:

setTimeout(function() { 
    repeat(); 
}, 8000) 

由于setTimeout重复,我假设repeat函数本身触发了另一个setTimeout它运行后再次调用自身(链setTimeout调用)。

如果是这样,你有两个选择:

  1. 有一个控制变量告诉repeat是否完成工作或没有。一个简单的布尔值就可以。当您想要repeat跳过它的工作并且repeat检查它时设置布尔值。这是最简单的答案。

  2. 有控制功能repeat,像这样:

    var repeatHandle = 0; 
    function startRepeat() { 
        if (!repeatHandle) { 
         repeatHandle = setTimeout(repeatTick, 8000); 
        } 
    } 
    function repeatTick() { 
        repeatHandle = 0; 
        repeat(); 
    } 
    function stopRepeat() { 
        if (repeatHandle) { 
         clearTimeout(repeatHandle); 
         repeatHandle = 0; 
        } 
    } 
    

    ...然后用它们来控制重复。请务必修改repeat以拨打startRepeat安排下一次呼叫,而不是直接呼叫setTimeout

2

setTimeout返回超时的ID。您可以存储该值,然后使用clearTimeout在需要时停止超时。

var timeout; 
$('#messages').click(function() { 
     $('#messagesDropDown').slideDown(function() { 
      clearTimeout(timeout); // Cancel the timeout when the slideDown has completed. 
     }); 
    }) 
    .mouseleave(function() { 
     $('#messagesDropDown').slideUp(); 
     clearTimeout(timeout); // Cancel incase it's still running (you can also set `timeout` to undefined when you cancel with clearTimeout, and apply some logic here (`if (timeout == undefined)` so you can leave it running rather than restarting it) 
     timeout = setTimeout(repeat, 8000); // Store the ID of the timeout 
    }); 

的setTimeout将设置重复性事件;它只会触发一次(如延迟事件)。请看setInterval(和clearInterval)。