views:

2166

answers:

4

I'd like a short smallest possible javascript routine that when a mousedown occurs on a button it first responds just like a mouseclick and then if the user keeps the button pressed it responds as if the user was continously sending mouseclicks and after a while with the button held down acts as if the user was accelerating their mouseclicks...basically think of it like a keypress repeat with acceleration in time.
i.e. user holds down mouse button (x=call function) - x___x___x___x__x__x_x_x_x_xxxxxxx

+2  A: 

When the button is pressed, call window.setTimeout with your intended time and the function x, and set the timer again at the end of x but this time with a smaller interval.

Clear the timeout using window.clearTimeout upon release of the mouse button.

Thomas
I was busy trying to write the code for him, but decided not to and in the mean time you posted this and it was exactly what I was working on. Very nice.
Jason Bunting
A: 

something like the psuedo code below might work..

var isClicked = false;
var clickCounter = 100;
function fnTrackClick(){
   if(isClicked){
      clickCounter--;
      setTimeout(clickCounter * 100, fnTrackClick);
   }
}

<input type="button" value="blah" onmousedown="isClicked=true;" onmouseover="fnTrackClick();" onmouseup="isClicked = false;" />
Quintin Robinson
+1  A: 

Just put the below toggleOn in the OnMouseDown and toggleOff in the OnMouseUp of the button.

var tid = 0;
var speed = 100;

function toggleOn(){
    if(tid==0){
        tid=setInterval('ThingToDo()',speed);
    }
}
function toggleOff(){
    if(tid!=0){
        clearInterval(tid);
        tid=0;
    }
}
function ThingToDo{

}
Glennular
+1  A: 
function holdit(btn, action, start, speedup) {
    var t;

    var repeat = function () {
        action();
        t = setTimeout(repeat, start);
        start = start / speedup;
    }

    btn.mousedown = function() {
        repeat();
    }

    btn.mouseup = function () {
        clearTimeout(t);
    }
};

/* to use */
holdit(btn, function () { }, 1000, 2); /* x..1000ms..x..500ms..x..250ms..x */
neouser99
thanks. i added a log function for the exponential curve rather than the linear but thats almost exactly what i was looking for.
zurk