[英]Wait for execution to complete before executing again
我想阻止我的点击处理程序多次执行,但是它没有按预期运行。 我的方法方向正确吗? 我希望当用户仅单击一次按钮时执行此处理程序。 当然,该处理程序可以再次执行(在执行完成之后)。
var init = false, i = 1; $('button').on('click', function() { if (init) { return; } init = true; (function() { // this for loop is for example purposes, just to have something running for (var i = 0; i < 5000; i++) { $('.text').append(i) } init = false; }()); $('.counter').html(i); i++ });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button">Button</button> <div class="text"></div> <div class="counter"></div>
尝试设置button
属性disabled
到true
在开始init
,使用.hide()
.delay()
.show()
设置disabled
属性为false
var count = 1, max = 5000, init = function() { $(this).prop("disabled", true) .off("click.count"); $(".counter").html(count); count++; $(this).hide(0, function() { for (var i = 0; i < max; i++) { $(".text").append(i); } }).delay(max / 2).show(function() { $(this).prop("disabled", false) .on("click.count", init) }) }; $("button").on("click.count", init);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <button id="button">Button</button> <div class="text"></div> <div class="counter"></div>
在这里尝试此解决方案。
首先,我们将click handler注册到button:
$('button').on('click', runThis );
这里是runThis()处理函数:
function runThis() {
// register off click handler on button
$('button').off('click');
// loop over i
for (var i = 0; i < 2000; i++) {
$('.text').append('<br/>' + i);
}
// if execution finish
if (i == 2000) {
// register back handler
addBack();
}
}
在这里,我们点击按钮上的点击处理程序:
function addBack() {
$('button').on('click', runThis );
}
在确定UI被阻塞之后,我研究了将循环“分块”成较小的循环的解决方案,以使UI变为不受阻塞并可以执行其他功能。
分块循环
function loop(arr, fn, before, callback) {
let index = 0,
step = 50,
stepTotal = step;
before();
(function chunk() {
while(index < arr.length && index < stepTotal) {
fn(arr[index], index);
index++;
}
if (index < arr.length) {
stepTotal+=step;
setTimeout(chunk, 0);
} else {
callback();
}
})()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.