zqk
zqk

Reputation: 75

javascript - make setTimeout faster?

My code is:

function slide(x) 
{
    if (x==undefined)
      var x = 1;
    if (x >= 4096) 
      return;

    document.getElementById("slide").style.backgroundPosition = x + "px 0px";
    x++;
    setTimeout(function() {
        slide(x);
    }, 1);
}

JSFIDDLE

It makes a spin (?) by changing backgroundPosition, and it works. But it's too slow, I'd want to make it faster, and then gradually slow down. How can I do that?

Upvotes: 1

Views: 1181

Answers (4)

Mario Tacke
Mario Tacke

Reputation: 5488

You should pick a higher delay than 1ms. In most browsers 10 to 50 ms would be a lot more reliable. To speed up your animation though, increase x increments. For example:

function slide(x) 
{
    if(x==undefined) var x = 1;
    if(x >= 4096) return;
    document.getElementById("slide").style.backgroundPosition = x+"px 0px";
    x += 10; // or some other value
    setTimeout(function() {
        slide(x);
    }, 50); // or some other value
}

Also, you probably want to check x like this: if (typeof x === 'undefined') { x = 1; }, no need for var.

2018 UPDATE: Check out the https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame API. Using this over a fixed update interval is usually preferable.

Upvotes: 2

yyf
yyf

Reputation: 25

I got it nicely starting fast and then going slower by adding to your code the following:

if(x < 1000)
    x+=2
else if(x < 1500)
    x+=1.5
else
    x++;

Upvotes: 1

Baro
Baro

Reputation: 5520

I have rewrite all the function:

  function slide() {
    var x = 1;
    var y = 30;
    var clr = setInterval(function(){
      if(x >= 4096) x = 1;
      document.getElementById("slide").style.backgroundPosition = x+"px 0px";
      x+=y;
      y-=0.1;
      if (y<=0) { clearInterval(clr); }
    },10);

  }

https://jsfiddle.net/tatrwkmh/4/

Upvotes: 1

Comptonburger
Comptonburger

Reputation: 594

Currently the position is being changed by 1 pixel every time slide is called, via the line x++;. You can make it faster by changing this from x++ to x += 2 or x += 3 etc.

Your animation may look clunky without some sort of easing function, though. You should look into using some sort of animation library instead.

Upvotes: 1

Related Questions