JavaScript while mousedown

29,184

Solution 1

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

Solution 2

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)
});
Share:
29,184
Larry
Author by

Larry

Updated on January 28, 2021

Comments

  • Larry
    Larry over 3 years
    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?