Rich_Rich
Rich_Rich

Reputation: 439

While MouseDown, first slowly decrease number, then increase decreasing speed (jQuery)

As the title suggests I'm stuck with a MouseDown problem. What I want in "pseudocode"

While ("#arrowUp").mouseDown(function() {
    counter++; //One time directly when pressed
    if(MouseDownTime > 500){ //500ms that is
       setTimeOut({counter++}, 75);  //Meaning, every 75ms counter++
    }

}

I have been looking around at Stack Overflow for over two days now. And I succeeded to increment every 75ms, but then I couldn't build in the if(MouseDownTime > 500)-statement, while still being able to increase the counter every 75ms after the 500ms.

$("#tempUp").mousedown(function() {     //When longer pressed, automatically faster increase Temperature
    int = setInterval(editTemp(currTemp+1), 250);
    })
                .mouseup(function() {
    clearInterval(int);
    numberOfRepeats = 0;        
    }); 

This is code I have of of my function so far. Could anyone help me out? Or am I asking the question in a wrong way? (non-constructive)

Upvotes: 2

Views: 2168

Answers (1)

ZiNNED
ZiNNED

Reputation: 2650

If I understand you correctly you can make use of a combination of setTimeout and setInterval, like so:

$(document).ready(function () 
{
    var temp = 0;
    var to   = null;
    var iv   = null;

    $("#ClickMe").on("mousedown", function () 
    {
        temp++;
        $("#Temp").html(temp);
        to = setTimeout(function () 
        {
            iv = setInterval(function () 
            {
                temp++;
                $("#Temp").html(temp);
            }, 75);
        }, 500);
    }).on("mouseup mouseleave", function () 
    {
        clearTimeout(to);
        clearInterval(iv);
    });
});

See this FIDDLE for an example.

EDIT: Added the mouseleave event as well as suggested by José F. Romaniello.

Upvotes: 9

Related Questions