2015-11-10 22 views
0

我有一個名爲customevent的事件。當這個事件發生時,我需要在div上切換一個類。當一個事件立即啓動一個函數,但等待x秒直到它能夠再次運行?

這是工作,但事件有時會快速連續發生多次。當發生這種情況時,課程會再次被添加和刪除,這不是我想要的。

$(document).on('customevent', function(event, data) { 
     $('.class').toggleClass('toggle-class'); 
    }); 

當事件發生時,我需要該類立即切換。然而,即使事件繼續發生,我也需要該班級無法切換1秒。以下不起作用。

var is_blocked; 

    $(document).on('customevent', function(event, data) { 
     if (is_blocked !== true) { 
     $('.class').toggleClass('toggle-class'); 
     is_blocked = true; 
     setTimeout(function(){ 
      is_blocked = false; 
     }, 1000); 
     } 
    }); 
+2

[禁用單擊事件處理程序的可能的複製持續時間](http://stackoverflow.com/questions/8335177/disable-click-event-handler-for-a-duration-of-time) – JNF

回答

1

爲什麼不將is_blocked設置爲時間戳而不是布爾值?喜歡的東西:

var blocked_time = 0; 

$(document).on('customevent', function(event, data) { 
    if (blocked_time + 1000 < new Date().getTime()) { 
     $('.class').toggleClass('toggle-class'); 
     blocked_time = new Date().getTime(); 
    } 
}); 
0

你都非常接近,但沒有SIGAR

var is_blocked = false; 

$(document).on('customevent', function(event, data) { 
    if (!is_blocked) { 

     $('.class').toggleClass('toggle-class'); 

     is_blocked = true; 

     setTimeout(function(){ 
      is_blocked = false; 
     }, 1000); 
    } 

    is_blocked = true; 
    //I'll be set to true, and in a second ill be false 
    //thanks to the timeout. This might not be a stable solution 
    //because what happens if the function is spammed for over a second? 
}); 

你需要每一個函數運行獨立於if-statement的時間設定is_blockedtrue

0

你可能想看看debounce(或lodash throttle)功能,這可能會喜歡這個

var throttled = debounce(function() { 
    // your actions will be executed at max 
    // once every 1000ms 
}, 1000); 

$(document).on('event', throttled); 

在主題中:https://davidwalsh.name/javascript-debounce-function

相關問題