我有一个相当大的复选框列表,当您选中/取消选中一个复选框时,它们都会执行一个操作:
$("input[type='checkbox']").change(function () {
DoSomething();
});
DoSomething()
方法实际上相当繁重。我遇到了一个问题,如果有人在短时间内开始单击多个复选框,则会导致每次都调用该方法,
我想对此进行限制,以便如果用户在一两秒内单击其中几个复选框,则它只会调用 DoSomething()
一次。
有没有办法在我调用 DoSomething()
之前等待几秒钟,直到用户检查完复选框?
最佳答案
将我的评论移至答案。
查看 _.throttle
/_.debounce
underscore.js中的方法。如果您愿意将其用作库,那么这正是您所需要的。否则,您可以只查看源代码并复制您需要的方法。
以下示例将在执行该函数之前自选中最后一个复选框后等待一秒钟:
var debouncedFunction = _.debounce(function() {
console.log('Debounced');
}, 1000);
$("input[type='checkbox']").change(debouncedFunction);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
如上所述,如果您不想在项目中包含下划线,那么您可以简单地抓取 _.debounce
方法。看看this example .
var debouncedFunction = debounce(function() {
console.log('Debounced');
}, 1000);
$("input[type='checkbox']").change(debouncedFunction);
function debounce(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = new Date().getTime() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = new Date().getTime();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
关于javascript - 修改复选框change()事件以等待其他操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33712450/