mousedown时的JavaScript

时间:2013-03-19 16:35:36

标签: javascript while-loop mousedown

var mdflag;
var count = 0;

document.addEventListener("mousedown",mdown,false);
    document.addEventListener("mouseup",mup,false);
}


function mdown()
{
    mdflag=true;
    while(mdflag)
    document.getElementById("testdiv").innerHTML = count++;

}
function mup()
{
    mdflag = false;
}

我想要在鼠标停止时运行代码,我无法找到任何建议我可以做的同时(mousedown)所以我试图为mousedown制作一个标志,这是在鼠标上重置然而我相信的同时循环是什么导致我陷入无限循环。

有任何建议可以帮助实现我的目标吗?

3 个答案:

答案 0 :(得分:14)

您必须在某个合理的时间间隔内调用mousedown活动。我这样做:

var mousedownID = -1;  //Global ID of mouse down interval
function mousedown(event) {
  if(mousedownID==-1)  //Prevent multimple loops!
     mousedownID = setInterval(whilemousedown, 100 /*execute every 100ms*/);


}
function mouseup(event) {
   if(mousedownID!=-1) {  //Only stop if exists
     clearInterval(mousedownID);
     mousedownID=-1;
   }

}
function whilemousedown() {
   /*here put your code*/
}
//Assign events
document.addEventListener("mousedown", mousedown);
document.addEventListener("mouseup", mouseup);
//Also clear the interval when user leaves the window with mouse
document.addEventListener("mouseout", mouseup);

答案 1 :(得分:5)

你不能这样做,因为你的函数必须在处理另一个事件之前结束,但你可以重复调用一个函数直到鼠标启动:

var timer;
document.addEventListener("mousedown", function(){
     timer=setInterval(function(){
          document.getElementById("testdiv").innerHTML = count++;
     }, 100); // the above code is executed every 100 ms
});
document.addEventListener("mouseup", function(){
    if (timer) clearInterval(timer)
});

答案 2 :(得分:0)

您需要使用 setInterval 来执行您的函数并使用 clearInternal 来停止

let interval = setInterval(function(){
    console.log("executing...");
}, 0);


document.addEventListener("mouseup", function(){
    clearInterval(interval); 
    console.log('End'); 
});