Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 785
Larry Avatar asked Mar 19 '13 16:03

Larry


2 Answers

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);
like image 164
Tomáš Zato - Reinstate Monica Avatar answered Sep 29 '22 04:09

Tomáš Zato - Reinstate Monica


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)
});
like image 36
drunken bot Avatar answered Sep 29 '22 03:09

drunken bot