How Many Setintervals Is Too Many In Good Practice?
Solution 1:
I would suggest any setinterval is too many, you should always use settimeout instead. The reason for this is that javascript is single threaded. This means that if some code (maybe the function in setinterval) blocks the timeout call, setinterval will continue to issue more calls to the function. With small intervals this can result in function calls stacking up causing EXTREMELY hard to find/reproduce bugs.
Best practice here is to just use settimeout within the function itself. So if you previously had:
function foobar()
{
// do some stuff
}
setInterval(foobar, 100)
You should change it to:
function foobar()
{
//do some stuffsetTimeOut(foobar, 100)
}
This has the added benefit that you can add a bit of logic in to check if you actually want to run the function again.
Solution 2:
If you are afraid of having multiple timers, use 1 timer and make the effects fire every nth time the timer counts down. It depends on what you are trying to do though.
Solution 3:
It really depends on how long each one takes to execute, and the delay between each.
Your browser will queue these calls up, so if you're worried about slowing down the user's browsing experience (or jerky animations), you can probably detect with some fairly simple timing code whether you are missing the desired interval. You could then reduce (or increase) the number of effects being shown as appropriate.
Post a Comment for "How Many Setintervals Is Too Many In Good Practice?"