问题
How can I make setInterval to increase speed gradually, like start from 1000 ms and than go down until 40 ms gradually in few seconds by 1 ms at a time.
Any thoughts?
This is my code:
setTimeout(function() {bonustimer = setInterval(function() { handleTimer2(rushcount); }, 40);}, 1000);
handleTimer2 = function() {
if(rushcount === -1) {
clearInterval(bonustimer);
} else {
$('.digit-wrapper').html(rushcount);
rushcount--;
}}
回答1:
Set interval probably wouldn't be what you want here, as you just end up killing it and redoing it on every iteration. Much easier to use setTimeout, possibly something like this:
(function () {
var interval = 1001;
timer = function() {
--interval;
//do your thing here
if (interval >= 40) {
setTimeout(timer, interval);
}
};
timer();
})();
Also note that if you only decrease the interval by one ms at a time, from 1000 down to 40, it takes quite a while to go through all those iterations. You can always replace --interval
by some other formula, like interval = interval*0.9;
(to reduce by 10% each iteration) or whatever formula you want.
回答2:
I guess the code by @OldGeeksGuide just stops when the interval reaches 40. Needs a little improvement ;)
(function () {
var interval = 1000;
timer = function() {
interval--;
//do your thing here
interval = interval < 40 ? 40 : interval;
setTimeout(timer, interval);
};
timer();
})();
Then you could maybe need to stop this loop by wrapping the setTimeout with some if condition ;)
来源:https://stackoverflow.com/questions/23004792/js-setinterval-increase-speed-gradually