View Full Version : Animations with loop vs setInterval
Agnus
25 Jun 2009, 1:55 AM
This is a generic javascript question. Changing element style properties in a loop does not work. For example:
<div id="box" style="position: absolute; width: 50px; height: 20px; background: red;"><div>
<script type="text/javascript">
onload = function() {
var box = document.getElementById('box');
var y = 0;
while (y < 1000) box.style.top = y++;
}
</script>
Now if we replace the loop with this:
setInterval(function() { box.style.top = y++; }, 50);
works alright. Why this is happening?
evant
25 Jun 2009, 2:02 AM
What do you mean it "doesn't work"? The top of the element gets sets correctly in both cases, but how long do you think it takes to execute a while loop 1000 times?
Ext.onReady(function(){
var el = Ext.getBody().createChild({
tag: 'div',
style: 'background-color: red; width: 100px; height: 100px;position: relative;'
}).dom;
var y = 0, old = new Date();
while (y < 1000){
el.style.top = y++;
}
var d = new Date();
console.log(d.getElapsed(old));
});
On my box it takes 15ms.
Agnus
25 Jun 2009, 3:08 AM
You are right about that. However even if I increase the loop to last longer, it still doesn't seem to render the individual frames:
while (y < 10000) box.style.top = ++y % 100;
Animal
25 Jun 2009, 10:09 AM
This is a generic javascript question. Changing element style properties in a loop does not work. For example:
<div id="box" style="position: absolute; width: 50px; height: 20px; background: red;"><div>
<script type="text/javascript">
onload = function() {
var box = document.getElementById('box');
var y = 0;
while (y < 1000) box.style.top = y++;
}
</script>
Now if we replace the loop with this:
setInterval(function() { box.style.top = y++; }, 50);
works alright. Why this is happening?
During the execution of the javascript thread, the browser's appearance is not updated.
It's only when the current event handler ends, and control returns into the browser that it updates the screen.
Agnus
26 Jun 2009, 12:04 AM
@Animal
Thank you, that sounds like a reasonable explanasion.
Powered by vBulletin® Version 4.1.5 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.