Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase javascript loop delay with easing

I need to count up from 1 to 60 but i want to count up with an easing, so for example it would go from 1 to 30 with a 100ms delay, after that i need to increase the delay so the counting will gradually slow down when it reaches 60. This is what i got so far(not much):

var i = 0;
var interval = setInterval(function(){
    i += 1;
    console.log(i);
    if(i == 60) {
        clearInterval(interval);
    }
}, 100);
like image 489
passatgt Avatar asked Dec 25 '22 17:12

passatgt


2 Answers

I'd use setTimeout(), something like this:

var delay = 100, count = 0;
function delayed () {
    count += 1;
    console.log(count);
    if (count > 30) {
        delay += 10;
    }
    if (count < 60) {
        setTimeout(delayed, delay);
    }
}
delayed();

A live demo at jsFiddle.

like image 74
Teemu Avatar answered Dec 28 '22 06:12

Teemu


Why not slow down continuously? Looks much nicer in my opinion. I updated the answer of @Teemu accordingly. See this fiddle.

var delay = 0, count = 0;
function delayed () {
    count += 1;
    console.log(count);
    //adjust to influence overall speed
    delay+=5; 
    if (count <60) {
        setTimeout(delayed, delay);
    }
}
like image 43
lex82 Avatar answered Dec 28 '22 06:12

lex82