Thalecress
Thalecress

Reputation: 3451

jQuery: Call function periodically while click is held

When an element is clicked, I want to call a function every n seconds until the mouse button is released.

How should I do this?

EDIT:

    var interval,
        i = 0;

    $("a").on("mousedown", function(){
           interval = setInterval(function(){ $(".results").append(i++); }, 250);
    });

    $(document.body).on("mouseup", function(){
           clearInterval(interval)
    });​

Upvotes: 0

Views: 465

Answers (2)

Joe Flateau
Joe Flateau

Reputation: 1235

Try this: http://jsfiddle.net/BDSUZ/

Upvotes: 3

SLaks
SLaks

Reputation: 888117

Call setInterval in the mousedown handler, then call clearInterval in mouseup.

Upvotes: 3

Related Questions