How to increase JavaScript loop delay with weakening

I need to count from 1 to 60, but I want to count with attenuation, so that, for example, it will go from 1 to 30 with a delay of 100 ms, after which I need to increase the delay so that the count gradually slows down when it reaches 60 This is what I got so far (not so much):

var i = 0;
var interval = setInterval(function(){
    i += 1;
    console.log(i);
    if(i == 60) {
        clearInterval(interval);
    }
}, 100);
+4
source share
3 answers

I would 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();

Live demo in jsFiddle .

+4
source

Here you can use. A bit of math in action

var i = 0, a = 0;
var interval = setInterval(function(){
    i += 1;
    a = parseInt(Math.log(i)*Math.log(i)*100, 10);
    print(i, a);
    if(i == 60) {
        clearInterval(interval);
    }
}, 100);

function print(i, a){
    setTimeout(function(){
        console.log(i)
    },a);
}

, a . , i

+2

Why not slow down continuously? It looks much better in my opinion. I updated @Teemu's answer accordingly. See this script .

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);
    }
}
+2
source

All Articles