/    Sign up×
Community /Pin to ProfileBookmark

setTimeout and global vars

Hello fellow web developers!

In connection with an ajax-game I’m creating for the moment, I have been running into a problem using setTimeout().

Even though I call setTimeout from inside af member of an object it uses global variables. This is very annoying! ?

The problem occurs for example when I’m using my “fader-function” (a function that fades html-elements in/out) on several elements at a time:

[code=html]for(i=1; 5>=i; i++) {
opacity = (fade_to == ‘1’) ? i/5 : 1-i/5;
setTimeout(“document.getElementById(‘” + obj_id + “‘).style.opacity = “+opacity, (i-1)*40);
}[/code]

The opacity-var and the obj_id var will be affected from other instances of the function if to faders are running simultaenously. This results in weird results – the elements are blinking instead fading nice and slow.

Am I using the setTimeout-function in a stupid way or what? What is the easiest way out of this? Suggestions are very welcome.

Thank you,
Rasmus

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@phpnoviceApr 05.2006 — You should have a separate, asynchronous function that performs the fade through an argument parameter that the function passes to itself through multiple iterations using the [b]setTimeoutp[/b] method. You start it as follows:

window.setTimeout("MyFader('" + obj_id + "')", 10);

Then this function iterates itself, again via setTimeout, passing two arguments to itself. No global variables required.
×

Success!

Help @Rasmus 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 6.16,
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: @nearjob,
tipped: article
amount: 1000 SATS,

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

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...