0

So I made a code

function slide()
{
    var x=1;
    while (x<=512) 
    {
        document.getElementById("slide").style.backgroundPosition = x+"px 0px";
        x++;
    }
}

JSFIDDLE

I want to make a transition from backgroundPosition - 0 to backgroundPosition 512. This code above changes immediately from 0 to 512, I want to make it like 1<100ms break>, 2, 3...
I tried change x++ to setTimeout(function(){x++), 100) but it doesn't do anything.

CoderPi
  • 12,985
  • 4
  • 34
  • 62
zqk
  • 75
  • 6
  • 3
    Whilst you can indeed do this with `setInterval` in JavaScript, would you alternatively be able to use an answer that uses CSS animations? – James Thorpe Dec 03 '15 at 17:25
  • 2
    Really, don't do this with JavaScript. Use CSS animations. Have a look at this for inspiration http://stackoverflow.com/questions/16989585/css-3-slide-in-from-left-transition – msanford Dec 03 '15 at 17:26

1 Answers1

1

Use setTimeout() and call function :

function slide(x) 
{
    if(x==undefined) var x = 1;
    if(x >= 512) return;
    document.getElementById("slide").style.backgroundPosition = x+"px 0px";
    x++;
    setTimeout(function() {
        // recall function and add other code if you want.
        slide(x);
    }, 100);
}
slide();
  • _Really_ minor nitpick - it should be `if (x > 512)` to match the OP's intent, or better still, do `if (x<=512)` before the call to `setTimeout`, so you save one invocation of the function at the end. – James Thorpe Dec 03 '15 at 17:29