Why do multiple setTimeout() calls cause so much lag?

后端 未结 2 1650
后悔当初
后悔当初 2021-01-18 09:51

I have a complex animation sequence involving fades and transitions in JavaScript. During this sequence, which consists of four elements changing at once, a setTimeout

2条回答
  •  长情又很酷
    2021-01-18 10:29

    Well, that's a lot of javascript (despite the "quadruple-dose of awesomeness" :)

    You're firing a lot of setTimeout sequence, I'm not sure how well JS engines are optimised for this.. particularly IE <= 8

    Ok, maybe just a rough suggestion... You could maybe write a small timing engine.

    Maintain a global object that stores your current running timed events with the function to run, and the delay...

    Then have a single setTimeout handler that check against that global object, and decreases the delay at each iteration and call the function when the delay becomes < 0

    you global event would looks something like that:

    var events = {
    
            fade1 : {
                fn : func_name,
                delay : 25,
                params : {}
            }
    
            fadeArrow : {
                fn : func_name,
                delay : 500,
                params : {}
            }
    
            slideArrow : {
                fn : func_name,
                delay : 500,
                params : {
                    arrow:some_value
                }
            }
    
        }
    

    then create a function to loop through these at an interval (maybe 10 or 20 ms) and decrease your delays until they complete and fire the function with params as a paramer to the function (check Function.call for that).

    Once down, fire setTimeout again with the same delay..

    To cancel an event just unset the property from the events list..

    Build a few method to add / remove queued events, update params and so on..

    That would reduce everything to just one timeout handler..

    (just an idea)

提交回复
热议问题