質問

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;
}

I'm wanting to run code while the mouse is down, i cant find anything to suggest i can do while(mousedown) so i've tryed making a flag for mousedown which is reset on mouse up however i beleive the while loop is whats causing me to go get stuck in an infinite loop.

Any advice to help with what i'm trying to acheive?

役に立ちましたか?

解決

You have to invoke the mousedown activity in some reasonable interval. I'd do this:

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);

他のヒント

You can't do that, as your function must end before another event is processed, but you could repetitively call a function until the mouse is up :

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)
});

You need to use setInterval to execute your function and clearInternal to stop

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


document.addEventListener("mouseup", function(){
    clearInterval(interval); 
    console.log('End'); 
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top