Bobh Bobh - 1 month ago 15
jQuery Question

SetTimeout only executes once on mousedown

All I am trying to do is to increment a number showing in a box by 1 and having it do that every 100 ms as long as mouse is down. The function executes, but never more than once no matter how long the mouse is held down. It only increments the variable by 1 each time there is a mousedown event on this element and I can see that in the box whereas I wanted to see the number keep increasing rapidly as long as the mouse stays down. Is there any code for the mouseup event that would stop this mousedown event from continuing to execute the function in setTimeout or is there a rule of some sort I am missing? Weird.

var mouseDownCount = 0;

$("#addButton").mousedown(function () { startMouseCount(); });

function startMouseCount() {
$("mouseCount").html(mousedownCount)

mdcTimer = window.setTimeout(function () {
mousedownCount++;
$("#mouseCount").html(mousedownCount);
}, 100);

return false;
}

May May
Answer Source

I guess you may want this:

var mouseDownCount = 0;
var mdcTimer;

$("#addButton").mousedown(startMouseCount);
$("#addButton").mouseup(stopMouseCount);

function startMouseCount() {
    mdcTimer = window.setTimeout(function () {
        mouseDownCount++;
        $("#mouseCount").html(mouseDownCount);
        startMouseCount();
    }, 100);
}
function stopMouseCount() {
    clearTimeout(mdcTimer);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<button id="addButton">button</button>
<h2 id="mouseCount"></h2>