tempse
tempse

Reputation: 51

JS - several setTimeout in a row?

Just a followup to this thread,

I'm making a picture move up and down, with the following code :

icon.style.top = top-50 + "px";
setTimeout ( function() { icon.style.top = top + "px"; }, 200) ;

Now i'd like to implement more intermediate positions. The idea is to induce a translation effect. I tried to stack setTimeout lines, but didn't work.

I'm reading some stuff about clearTimeout right now, but probably your help will make it work just better. Thanks !

Upvotes: 3

Views: 1327

Answers (1)

Travis J
Travis J

Reputation: 82337

You can "stack" the setTimeout calls if you want. Just remember that they are called immediately and only take action after the given millisecond argument.

So if I want three callbacks to take place within 200 milliseconds of each other, using 200 as the argument is incorrect. The first one should be 200, and then 400, and then 600 - or to break it out i * 200 where i is the iterator.

var offsets = [-50,50,0,-100,100,0];   //some set of pixel offsets
var timing = 200;   //the 200 millisecond argument
for(var i = 0; i < offsets.length; i++){   //loop through offsets with i
    (function(i){ //close over the i value to ensure the value is saved
    setTimeout( function() {   //setup the timeout
        icon.style.top = (top+offsets[i]) + "px";   //change the style offset
    }, timing*i);   //multiply the 200 milliseconds by loop counter
    })(i)   //close over the i value
}

Upvotes: 2

Related Questions