[英]Running a function after a certain period of time without holding up the execution thread
[英]On / Off function after a certain period of time
想知道如何使.off()僅在特定時間段內發生。 我有一個div,一旦單擊,我想禁用click事件2秒鍾,然后允許再次單擊。 目前我所能做的就是單擊div,然后單擊它就關閉了。
這是我要問的簡短示例:
$('.test').on('click', function() {
// *do stuff*
$('.test').off('click'); *for a certain perdiod of time*
});
使用布爾變量作為標志來聲明是否應執行單擊處理程序,而不是附加/分離多個元素中的事件,是一項非常簡單的任務。 嘗試這個:
var clickEnabled = true;
$('div').click(function() {
clickEnabled = false;
setTimeout(function() {
clickEnabled = true;
}, 2000);
});
$('.test').on('click', function(e) {
if (!clickEnabled) {
e.preventDefault();
} else {
// do stuff...
}
});
請注意,您還應該使禁用.test
的事實在用戶界面中可見,否則,當訪問者單擊需要執行操作的元素時,它們只會使訪問者感到困惑和煩惱,但是什么也不會發生。
一段時間后激活怎么辦?
function myFunction() {
...do stuff
$('.test').off('click'); for a certain perdiod of time
setTimeout(function(){ $('.test').on('click', myFunction)}, 2000);
}
使用setTimeout,您可以執行以下操作:
var enabled = true;
var timeoutSeconds = 2;
$(function () {
$('.test').on('click', function(e) {
if (enabled) {
// *do stuff*
enabled = false;
window.setTimeout(function() {
enabled = true;
}, timeoutSeconds * 1000);
} else {
e.preventDefault();
}
});
});
您可以這樣做。
function onClick() {
// do stuff here
$('.test').off('click');
setTimeout(function(){
$('.test').on('click', onClick);
}, 2000)
}
$('.test').on('click', onClick);
或者您可以使用css和toggleClass做到這一點
// css
.disabled {
pointer-events: none;
}
// js
$('.test').on('click', function(){
// do stuff here
$('.test').addClass('disabled');
setTimeout(function(){
$('.test').removeClass('disabled');
}, 2000);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.