Setinterval with exponential reduction in time

I have a mousedown event with setinterval. I want the interval time to be variable. So, the first one is 500, the second 500/2 = 250, etc. Any tips?

$plus.mousedown(function(e) { increment(20) timeout = setInterval(function(){ increment(20) }, 500); }); $(document).mouseup(function(){ clearInterval(timeout); return false; }); 

Hooray!

EDIT: sorry for the ambiguity. I want the interval time to change during the musculature. Thus, while mousedown is running, the time interval should change. Therefore, not every mouse click, but with each continuous click, and then reset again.

+3
source share
2 answers

You cannot do this with setInterval() unless you save the cleanup to change the delay, so you can write a wrapper around setTimeout() to do something like this:

 function easingTimeout(delay, fn) { var id, invoker = function() { fn(); delay = Math.floor(delay / 2); if (delay) { id = setTimeout(invoker, delay); } else { id = null; } } // start it off id = setTimeout(invoker, delay); return { clear: function() { if (id) { clearTimeout(id); id = null; } } } 

For use:

 var timeout; $plus.mousedown(function(e) { increment(20); timeout = easingTimeout(500, function() { increment(20); }); }); $(document).mouseup(function(){ timeout.clear(); return false; }); 
+5
source

This solution is not dependent on jQuery:

 var timeoutInterval = 500; var mousedown = false; function incrementAndWait() { if (!mousedown) return; increment(20); timeout = setTimeout(incrementAndWait, timeoutInterval); timeoutInterval /= 2; } document.onmousedown = function() { timeoutInterval = 500; // Reset to 500 to allow multiple mousedown/mouseup mousedown = true; incrementAndWait(); }; document.onmouseup = function() { mousedown = false; } 

You can add console.log((new Date).getTime(), 20); to the incrementAndWait method to see the numbers going to the console. It's fun to play with something :)

+1
source

All Articles