[英]Fire function on click only one time each second (jQuery)
I have a button on a page, that I want to be fired maximum once every second. 我在页面上有一个按钮,希望每秒被激发一次。 Meaning that if the user click on it like a madman for five second, it will only be executed five times.
这意味着,如果用户像疯子一样单击它五秒钟,它将只会执行五次。 I've been googling and searching Stack, with no results.
我一直在谷歌搜索和搜索堆栈,没有结果。 Also tried Alman's throttle/debounce plugin, but doesn't seem to work on clicks.
还尝试了Alman的油门/反跳插件,但似乎对点击不起作用。
Why not disable the button for 1 second in the click event for the button? 为什么不在按钮的单击事件中禁用按钮1秒钟?
$('#my_button').click(function() {
/*
your logic here
*/
// disable the button for 1 second
$(this).attr('disabled', 'disabled').delay(1000).removeAttr('disabled');
}
Create a throttle that ends the event unless it has been 1 second since the previous click. 创建一个结束事件的节流阀,除非自上次单击以来已过1秒。
var clicked = false;
$(element).click(function(e){
e.preventDefault();
if (clicked) {
return;
}
clicked = true;
console.log("Do Stuff");
setTimeout(function(){
clicked = false;
},1000);
});
Or you can use a data property to avoid the extra variable: 或者,您可以使用数据属性来避免额外的变量:
$(element).click(function(e){
e.preventDefault();
if ($(this).data("clicked")) {
return;
}
$(this).data("clicked",true);
console.log("Do Stuff");
setTimeout(function(){
$(this).data("clicked",false);
},1000);
}).data("clicked",false);
use a timer 使用计时器
var clicked = false;
setInterval(function(){
clicked = false;
},5000);
if($('.button').click(function(){
if(!clicked){
do job;
clicked = true;
}
});
Try this instead : 试试这个代替:
$(function(){
var currentTime = (new Date()).getTime();
$("input:button").click(function(){
var nowTime = (new Date()).getTime();
var diff = Math.abs((nowTime - currentTime)/1000);
if(diff < 1)
return;
currentTime = nowTime;
// do your stuff
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.