0

Does setTimeout work from WITHIN setInterval?

I'm writing some JavaScript to animate some DOM elements for a strange artistic project. The best way for me to explain my question is to give an example:

I have 50 different divs that I need to animate by changing their position on screen, using setInterval. I need each div to be moving at a different rate.

The solution I planned to use was to have a sleep function within my larger changePosition function, so that I could pass a different sleep value for each div. This way, I could assign a unique rate of movement for each div via a dictionary.

The issue that I'm having is that JavaScript does not have "sleep". It only has setTimeout, which does not seem to be working from within my setInterval loop.

Joseph
  • 117,725
  • 30
  • 181
  • 234
pepperdreamteam
  • 2,772
  • 3
  • 17
  • 15

2 Answers2

4

setTimeout() works perfectly inside of setInterval(), but since you're trying to emulate sleep() which javascript does not do or have, it sounds to me like you are trying to write synchronous code when setTimeout() works asynchronously. You will need to rethink how you write your code to do this.

Post some of your code and we can help a lot more specifically.

I'm not entirely sure I follow what you're trying to do, but it's probably easiest to animate N different things each at a different rate by just using a separate timer for each object. Each object's timer can then be set at it's own rate and detect it's own completion and you don't have to manage them all from some central timer.

In addition, if you're writing animation routines from scratch in javascript, you're doing a lot more work than you need to. This problem has been solved thousands of times already and there's no reason you have to invent it yourself all over again. A simple Google search for "javascript animation examples" will show all sorts of samples and plenty of code you can base yours off of. Here's a good tutorial: http://javascript.info/tutorial/animation.

The popular libraries like jQuery have all sorts of built-in functions for animation that do a lot of the dirty work for you also. Animation can also be done using CSS3 in modern browsers (other than IE).

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

Maybe you are looking for jQuery delay() function? http://api.jquery.com/delay/

And here: Can I use .delay() together with .animate() in jQuery? you can see how delay() and animate() functions works together.

Community
  • 1
  • 1
Alberto Fortes
  • 562
  • 4
  • 13