Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Animations stall when running javascript function

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.

like image 958
Christian Bankester Avatar asked Jan 16 '13 20:01

Christian Bankester


1 Answers

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.

like image 101
Alex Wayne Avatar answered Oct 22 '22 10:10

Alex Wayne