CSS Animations stall when running javascript function

时光总嘲笑我的痴心妄想 提交于 2019-12-10 15:12:38

问题


Let's say I have this javascript function:

   function pauseComp(ms) {
     var date = new Date();
     var curDate = null;
     do { curDate = new Date(); }
     while(curDate-date < ms);
    }

and a css3 animation (for instance, <i class="icon-spinner icon-spin"></i> from the new font-awesome 3). When I run the javascript function above, it stops the spinner while the function is running. See what I'm talking about here. Basically, javascript stops css animations, and I'm wondering why, or if anyone else has noticed this/found a workaround. I've tried putting it in a setTimeout(fn,0), where fn is the long process, but then realized why that will also not work (js is not multithreaded). Anyone seen this happening?

Update: Interestingly, it looks like this isn't as much of a problem in Safari, although interaction with the browser interface is still being affected.


回答1:


A browser page is single threaded. Updating the UI happens on the same thread as your javascript program. Which also means that any animation will not draw new frames while Javascript code is being executed. Typically, this is no big deal because most JS code is executed very quickly, faster than a single animation frame.

So the best advice is simply this: Don't do that. Don't lock up the JS engine for that long. Figure out a cleaner way to do it.


However, if you must, there is a way. You can get an additional thread via HTML5's Web Workers API. This isn't supported in older browsers, but it will allow you to run some long running CPU sucking code away from the main webpage and in it's own thread, and then have it post back some result to your page when it's done.



来源:https://stackoverflow.com/questions/14367168/css-animations-stall-when-running-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!