0

I'm making a little countdown bar with a css transition:

.livebar {
  background-color: black;
  transition: width 15s linear;
  width: 100%;
  height: 5px;
}

This code doesn't work (in Chrome), in the sense that there is no transition. The width goes to 0 immediately:

$("#barbag").append("<div class='livebar'></div>");
$(".livebar").css("width", "0");

...but this code works beautifully:

$("#barbag").append("<div class='livebar'></div>");
setTimeout(function(){$(".livebar").css("width", "0")}, 1);

Also, doing the two statements separately in the console works, but pasting in both fails.

It seems like Chrome needs some time after creating the .livebar div to make the transition "active". Is this a known bug, or am I doing something wrong, or is something entirely different going on?

Lars P
  • 796
  • 6
  • 16

2 Answers2

1

I think it has something to do with event loop

event loop process functions from stack, and setTimeout uses a callback function going to get queued in a stack whereas (".livebar").css("width", "0"); is just going to run as soon as processor sees it.

Zero delay doesn't actually mean the call back will fire-off after zero milliseconds. Calling setTimeout with a delay of 0 (zero) milliseconds doesn't execute the callback function after the given interval. The execution depends on the number of awaiting tasks in the queue.

So in your case the animation has to wait for $("#barbag").append(""); to finish first then apply css. Therefor it needs to be queued in stack, or it will trigger too early.

Zhang Bruce
  • 884
  • 1
  • 8
  • 23
0

You can use this code for fix issue:

Demo: https://output.jsbin.com/basusos

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script> 
$(document).ready(function() {
    $("#barbag").append("<div class='livebar'></div>");
    $(".livebar").stop(true, true).animate({width: 0}, 100 ); 
});
</script>
</head>
<body>
  <div id="barbag">Animate Width Zero</div>
</body>
</html>
Chandra Kumar
  • 4,127
  • 1
  • 17
  • 25