这是我的代码:
var mouseDown = false;
document.body.onmousedown = function() {
console.log("MOUSE DOWN");
mouseDown = true;
increaseRad();
}
document.body.onmouseup = function() {
console.log("MOUSE UP");
mouseDown = false;
}
function increaseRad(){
rad = 0;
while(mouseDown){
console.log("mouse is still down");
rad++;
console.log(rad)
}
}
当我按下时,increaseRad
运行,但内部的while循环永远不会结束。
知道为什么吗?
答案 0 :(得分:2)
这里的问题是你的代码作为阻塞循环运行。
while(mouseDown){
console.log("mouse is still down");
rad++;
console.log(rad)
}
浏览器在单个线程中评估Javascript,并且此循环永远不会暂停,以允许浏览器处理这些事件处理程序。
相反,你可以使用异步函数来监听mousedown事件,然后启动一个计时器。如果计时器结束时鼠标仍然按下,那么您可以将其视为长按。
var mouseIsDown = false;
window.addEventListener('mousedown', function() {
mouseIsDown = true;
setTimeout(function() {
if(mouseIsDown) {
// mouse was held down for > 2 seconds
}
}, 2000);
});
window.addEventListener('mouseup', function() {
mouseIsDown = false;
});
这些异步操作(addEventListener
,setTimeout
)不会阻止主线程。
答案 1 :(得分:0)
如果连续单击服务器次数,则会出现错误的单击并按住。更好的解决方案是...
var mouseIsDown = false;
var idTimeout;
window.addEventListener('mousedown', function() {
mouseIsDown = true;
idTimeout = setTimeout(function() {
if(mouseIsDown) {
// mouse was held down for > 2 seconds
}
}, 2000);
});
window.addEventListener('mouseup', function() {
clearTimeout(idTimeout);
mouseIsDown = false;
});