/    Sign up×
Community /Pin to ProfileBookmark

setTimeout puzzle

I’m not sure what I’m missing here, but for some reason the setTimeout method is executing all at once instead of chaining one after another as I expect it to: (under [B]this.start[/B])

Animation.js

[CODE]
function Animation(el){
var queue = [];
var pos = 0; //position in queue
var me = this;

function _getX(){
// To do: runtime style
return parseInt(el.style.left,10);
};

function _getY(){
// To do: runtime style
return parseInt(el.style.top,10);
};

function _moveBy(obj){
// To do: +/-
_setX(_getX() + obj.x);
_setY(_getY() + obj.y);
if(obj.callBack){
obj.callBack();
}
};

function _moveTo(obj){
// To do: +/-
_setX(obj.x);
_setY(obj.y);
if(obj.callBack){
obj.callBack();
}
};

function _setX(x){
el.style.left = x + “px”;
};

function _setY(y){
el.style.top = y + “px”;
};

this.start = function(ms){
var obj = queue[pos];
if(obj){
obj.action(obj);
pos++;
window.setTimeout(me.start,ms);
}
};
this.moveBy = function(obj){ //{x:100, y:100, callBack:fn}
obj.action = _moveBy;
queue[queue.length] = obj;
return me;
};
this.moveTo = function(obj){ //{x:100, y:100, callBack:fn}
obj.action = _moveTo;
queue[queue.length] = obj;
return me;
};

}
[/CODE]

html:

[CODE]
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />
<title>Animation</title>

<style type=”text/css”>
button{
position:absolute;
width:100px
}
</style>

<script type=”text/javascript” src=”Animation.js”></script>

<script type=”text/javascript”>
function test(){
var Actor = new Animation(document.getElementById(“Actor”));

Actor
.moveBy({x:10,y:10})
.moveBy({x:10,y:10})
.moveBy({x:40,y:50})
.moveBy({x:100,y:5})
.moveBy({x:50,y:50})
.moveBy({x:0,y:50})
.moveTo({x:100,y:100})
.moveBy({x:10,y:0})
.moveBy({x:10,y:0})
.moveBy({x:101,y:10})
.moveBy({x:0,y:10})
.moveBy({x:0,y:100})
.moveTo({x:10,y:10,callBack:function(){
alert(“Complete!”);
}})
.start(1000);
}
</script>

</head>
<body>
<button id=”Actor” style=”top:10px;left:10px” onclick=”test()”>Test</button>
</body>
</html>
[/CODE]

Any ideas?

to post a comment
JavaScript

1 Comments(s)

×

Success!

Help @TNO spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...