2011-05-26 163 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)。