我编写的代码在用户点击它时在画布上为点着色。点通过淡入动画进行着色,因此为给定点着色需要一定的时间。如果用户在前一个点仍然着色时单击一个新点,则会出现问题:产生异常颜色,淡入动画无限期地继续而不停止等等。
我希望这样做,以便当用户点击某个点时,忽略任何后续点击,直到该点的功能着色完成为止。完成后,用户应该能够单击另一个点来为其着色(即应该恢复onClick着色功能)。
在搜索此问题的解决方案时,我主要发现为仅执行一次的事件设计的代码。但是,这不是我需要的。我的用户应该能够触发任意数量的着色事件 - 我只是不希望任何这些事件同时发生,就像它一样。谢谢你的帮助!
答案 0 :(得分:1)
您可以使用锁定,例如:
var block = false;
element.addEventListener("click", function () {
if (block === true) {
return;
}
block = true;
doOperation("params", function () {
block = false;
});
});
function doOperation(input, callback) {
setTimeout(callback, 1000);
}
这会阻止点击约1秒钟。
通常你会使用promises而不是回调:
var block_promise = null;
element.addEventListener("click", function () {
if (block_promise === null || block_promise.is_resolved() === false) {
return;
}
block_promise = doOperation("params");
});
function doOperation(input, callback) {
var promise = new Promise();
setTimeout(function () {
promise.resolve();
}, 1000);
return promise.promise();
}
请注意,JavaScript中本身不支持Promises。使用您喜欢的图书馆。
答案 1 :(得分:0)
如果你有一种在绘画时设置标志的方法,你可以试试这个。这里我在绘画开始时将标志设置为true,在完成时将其设置为false。在buttonClick()函数中,如果绘制为真,我会立即退出。
<!DOCTYPE html>
<html>
<head>
<title>Button Test</title>
</head>
<body>
<script>
var painting = false;
var clicks = 0;
function buttonClick() {
//if painting, immediately exit buttonClick
if (painting)
return;
//display click count whenever we enter here
clicks++;
var obj = document.getElementById("clicks");
obj.value=clicks;
//simulate painting
painting = true;
document.getElementById("status").innerHTML = "painting in progress";
setTimeout(function() { colorPoint()}, 10000 /* 10 seconds */ );
}
function colorPoint() {
//simulated painting
painting = false; //allows button to be clicked again
document.getElementById("status").innerHTML = "painting done";
}
</script>
<button onclick="buttonClick()">Click me</button>
Button clicks: <input type="text" name="clicks" id="clicks">
<div id="status"> </div>
</body>
</html>