/    Sign up×
Community /Pin to ProfileBookmark

trouble with javascript time out

I’m trying to create a counter where it counts from 60 seconds to zero so i made use of the setTimeout function of javascript inside a loop.

[CODE]
var i = 60;

while(i >= 0)
{
setTimeout(theUpdateMethod, 1000);
i–;
}
[/CODE]

given the code above, in every second, the textbox’s value is changed with whatever the value of “i” is..

But the problem is the browser halts for 60 seconds, then displays 0. What is the alternative to displaying the value of “i” in everysecond without halting the browser?

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@voidvectorJan 27.2009 — setTimeout does not do what you think it does. setTimeout simply schedules a function to run x milliseconds from the point where setTimeout is called. As for the script, instead of waiting for that function to run, the script would continue with the next line immediately! So for your script, "i" would be decremented to -1 almost immediately.

For your case setInterval is actually more appropriate. To get the decrement you want, you need to move i-- into the theUpdateMethod. You need to unschedule the interval when it is done, use clearInterval.
×

Success!

Help @it2051229 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.18,
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,
)...