Why is CSS animation delayed?

I am trying to install an “update” image rotating during a long-term JS function. I add a class ("spinning") using the jQuery I defined in my CSS to trigger the animation - this works fine when you run it yourself. However, when I follow addClass with a JS function call with a long version, there is a delay in the animation, although the class is applied instantly.

Can someone show me where I'm wrong and how to get the animation to run before the long-runnning function starts?

This JSFiddle illustrates the problem: http://jsfiddle.net/gLas4k23/2/ - the rotation starts before the completion of "doSomething", but after a noticeable delay, which is absent if the doSomething call is missing.

html:
<div id='updateIcon' class='update'></div>

css:

.update {
    width: 40px;
    height: 40px;
    background: url("http://s24.postimg.org/4psxulnkh/update_light.png") no-repeat;
    background-size: 40px;
    cursor: pointer;
}

.update.spinning {
    -webkit-animation: spinner 1s infinite linear;  
}

@-webkit-keyframes spinner {
  from {
    -webkit-transform: rotate(0deg);
  }
  to { 
    -webkit-transform: rotate(360deg);
  }
}

JS:
$('#updateIcon').on('click', function(e){
    console.log('i have been clicked');
    $('#updateIcon').addClass('spinning');
    doSomething();
})


function doSomething(){
 console.log('doing something')

 for(var i=0;i<20000;i++){
     console.log('waiting');
 }

}
+4
source share
2 answers

This is because the loop formust end before the animation starts. Once you delete this loop, the animation starts immediately.

Take a look: http://jsfiddle.net/gLas4k23/4/

I think you need to use the function setTimeout()to get the desired result.

+2
source

Fiddle, console.log. . .

-1

All Articles