The two fundamental ways to do UI loops in JavaScript on browsers are setTimeout
and setInterval
:
setTimeout
will call a function after a specified interval in milliseconds. The timing is not necessarily precise, and you can't usually schedule something for within 10ms on browsers. It returns a handle you can use to cancel the callback (if you get to it before it happens) via clearTimeout
. To do a loop, you set a new timeout when you're done processing the previous one.
setInterval
will call a function repeatedly at the given interval (also in milliseconds, also with a typical 10ms minimum). It returns a handle you can use to stop the repeats via clearInterval
. You don't have to start a new one each time, the interpreter does the looping for you.
Which you choose depends on both what you're trying to do and personal preference. Note that the intervals in setInterval
are counted from when the callback was called, whereas if you schedule a new setTimeout
at the end of your callback processing, it'll obviously be scheduled from that point instead. If your processing takes any significant time, the difference can be important (but again, which you want depends entirely on the problem you're solving).
I think of "duration" as how long the effect as a whole takes to run, which would lie outside of either of these -- it would be a function of your effect code. Most effects I've seen run in steps (not sure how else you'd do them) and figure out how many steps to take on the basis of what duration you give them and what maximum granularity the author thought was needed. For instance, fading from white to black can take 255 steps if you want it to, but that might be too slow (and we'll leave aside discussions of "easing" where steps are adjusted according to how the human eye and mind perceive them). You might do it in 10 steps with a step every 50ms if you were told to take a total of half a second, but you might do it in 20 steps at the same interval if you had a full second to do it. Etc.