Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

setTimeout only delays first time in loop

0 views
Skip to first unread message

ba...@polisource.com

unread,
Sep 13, 2006, 10:14:17 AM9/13/06
to
I'm having a problem creating a delay before each list item gets moved
( http://www.polisource.com/PublicMisc/list-splitter-timeout-bug.html
). Choose any number of columns, vertical layout, and view as a web
page. They'll be a small delay before the entire bunch of list items
converts from left-to-right to top-to-bottom order. I expected a delay
before each item is moved. It looks like I have to flush the buffer to
get setTimeout to work, but I don't think there's a built-in flush
function in Javascript anymore. Or else setTimeout only delays the
function it calls the first time it's called and subsequently calls the
function with no delay. In this script I have:

setTimeout("funtest(" + li_count + "," + pos_change_left + "," +
pos_change_top + ")",700);

which calls:

function funtest(aaa,bbb,ccc)
{
var li = $('mylist').getElementsByTagName('LI');
li[aaa].style.position = 'relative';
li[aaa].style.left = bbb + 'px';
li[aaa].style.top = ccc + 'px';
}

once for each li that's moved (20 of them), but there's only one delay,
then they're all moved. If I put an alert in the function, it's
triggered 20 times, once before every change in position of a li, so
why aren't there 20 delays (one before each move) instead of just one?

Erwin Moller

unread,
Sep 13, 2006, 10:32:50 AM9/13/06
to
ba...@polisource.com wrote:

Hi,

Not my area of expertise, but I think I heard somebody in here say before
that all stylesheet-updates are executed when the JS-function returns.
Has something to do with 1 thread for javascript, but I am not sure.

It has nothing to do with 'flushing a buffer'. Which buffer?

And if you want them to move one after each other, give the next setTimeOut
from within the excuting function (funtest in this case).
Or make sure all setTimeout calls have an increasing interval.
Like this:
setTimeout("funtest('bla','bla','bluh')",700);
setTimeout("funtest('bla','bla2','bluh')",1400);
etc.

I cannot see by your code where and how the setTimeOut is implemented right
now.

Regards,
Erwin Moller

Jim Davis

unread,
Sep 13, 2006, 11:09:58 AM9/13/06
to

<ba...@polisource.com> wrote in message
news:1158156857.6...@h48g2000cwc.googlegroups.com...

>snip<

> setTimeout("funtest(" + li_count + "," + pos_change_left + "," +
> pos_change_top + ")",700);

>snip<

> once for each li that's moved (20 of them), but there's only one delay,
> then they're all moved. If I put an alert in the function, it's
> triggered 20 times, once before every change in position of a li, so
> why aren't there 20 delays (one before each move) instead of just one?

The key is going to be how you're calling that timeout. My guess is you've
put it in a loop and set 20 timeouts - think about it: of course they'd all
move at the same time (or very close) since you're setting them all at once.
;^)

There are at least two ways to manage this.

First you could have your timeout call a function which itself resets the
timeout with new information.

For example this structure (non-functional since I don't know how you set
your parameters) would call the function "funtest" every 700 ms ():

function funtest(aaa,bbb,ccc) {
var li = $('mylist').getElementsByTagName('LI');
li[aaa].style.position = 'relative';
li[aaa].style.left = bbb + 'px';
li[aaa].style.top = ccc + 'px';

// Call the same function again


setTimeout("funtest(" + li_count + "," + pos_change_left + "," +
pos_change_top + ")",700);
}

This style can be easier to understand since there's only one timeout active
at any moment: it's a relay race with twenty legs. One runner runs to
another who then starts to run as the first stops. Only one runner is in
motion at a time. Each runner runs the same distance.

The second option (and, if I'm correct that you've place the timeout in a
loop then probably the easier one for you) is to stagger the timeouts.
Assuming "li-count" is a counter index you could simply add this:

setTimeout("funtest(" + li_count + "," + pos_change_left + "," +

pos_change_top + ")", li_count * 700);

Note that the timeout is now "li_count * 700". This makes the timeouts set
to 700, 1400, 2100, 2800, etc. In the end you have 20 individual timeouts
but they all trigger, in order, at 700ms intervals.

Instead of a relay race this is a foot race with 20 people but each person
has to run a different distance.

This is simple and should work fine for 20 elements: but remember that a
timeout object does consume resources. If you want to scale up to large
numbers this may start to slow down and/or start to chew up memory (the
browser implementation of timeouts will be important here... I've never
tested huge numbers of timeouts but I would warrent there are browser
differences).

In any case I think the second solution will get you going well enough...
but the first generally seems to be the prefered solution I think.

Jim Davis


ba...@polisource.com

unread,
Sep 13, 2006, 1:29:22 PM9/13/06
to
Thanks guys. I incremented the delay for each iteration and it worked.

Jim Davis wrote:

> The key is going to be how you're calling that timeout. My guess is you've
> put it in a loop and set 20 timeouts - think about it: of course they'd all
> move at the same time (or very close) since you're setting them all at once.
> ;^)

I'm not sure I understand how the script is executed for it to work the
way it does. The way I figured, my original timeout said "delay 700ms,
then execute the named function (funtest)," then after funtest is
executed (which changes the position of a single li element), the
statement after the timeout is executed, which is within the same loop
of the timeout, and the loop would cause the timeout to be executed
again, causing another 700ms delay before another li changes position.

But as far as I could tell, you're saying that Javascript sees the
delay the first time, delays 700ms, then thinks "ok, I delayed 700ms
before funtest, and even if I encounter the 700ms timeout 19 more
times, that job was done so I don't have to delay again, but I still
have to execute funtest each time."

Anyone know of any online documentation for setTimeout that makes it
clear that the latter is the way it works rather than the former, or is
there a problem with my logic?

drclue

unread,
Sep 13, 2006, 1:34:43 PM9/13/06
to


Well , there are a few ways to do this, but decoupling
the creation,loop,event etc from the animation tends to work well for
me. This is just some off the cuff pseudo code (untested).

With the assumption that your creation loop actually will create
whatever elements faster then the 700 millisecond interval,
you would in each loop of the creation append the target object (li)
to the oAnimation.aTargets array. In that creation loop,
if oAnimation.aTargets.length == 1 then you call the intervalFunction
which will set the interval and cancel it once it catches up with
the created items


var oAnimation={iWas:0,iNow:0,idInterval:null,iInterval:700,aTargets:[]}

function intervalFunction()
{
oAnimation.iNow=oAnimation.aTarget.length
// If we are done . cancel the interval and reset
if(oAnimation.iWas>=oAnimation.iNow)
{
if(oAnimation.idInterval)
clearInterval(oAnimation,idInterval)
oAnimation={iWas:0,iNow:0,idInterval:null,aTargets:[]}
return;
}
// If this is our first call set the interval
if(oAnimation.idInterval==null)
{
oAnimation.idInterval=
setInterval("intervalFunction()",oAnimation.iInterval)
return
}
oAnimation.iNow=oAnimation.aTargets.length
if(oAnimation.iWas<oAnimation.iNow)
{
callYourAnimationFunction(oAnimation)
oAnimation.iWas++
}
}

ba...@polisource.com

unread,
Sep 14, 2006, 3:13:51 AM9/14/06
to
I received a response from TheBearMay at
http://www.webdeveloper.com/forum/showthread.php?p=637609 that
clarified things for me. "SetTimeout is not a thread delay, but a
function to run a command after a delay; i.e. it doesn't stop thread
execution, but spawns another thread on a time delay." That explains
the behavior. I hadn't read that anywhere. I guess someone learning
Javascript should buy a book. Some important information is missing
from the online documentation I've seen.

Dr John Stockton

unread,
Sep 14, 2006, 10:32:11 AM9/14/06
to
JRS: In article <1158168562.1...@d34g2000cwd.googlegroups.com>,
dated Wed, 13 Sep 2006 10:29:22 remote, seen in
news:comp.lang.javascript, ba...@polisource.com posted :

>But as far as I could tell, you're saying that Javascript sees the
>delay the first time, delays 700ms, then thinks "ok, I delayed 700ms
>before funtest, and even if I encounter the 700ms timeout 19 more
>times, that job was done so I don't have to delay again, but I still
>have to execute funtest each time."
>
>Anyone know of any online documentation for setTimeout that makes it
>clear that the latter is the way it works rather than the former, or is
>there a problem with my logic?

The latter.

All sound Javascript references, except the most condensed, indicate
that setTimeout causes the given code to be started after (at least) the
given delay, and do not say that the current thread of execution stops
for that delay.

Example :
setTimeout Evaluates an expression or calls a function once after a
specified number of milliseconds has elapsed.
...
setTimeout does not stall the script. The script
continues immediately (not waiting for the timeout to
expire). The call simply schedules a future event.

Newsgroup FAQ 4.20 is also clear enough.

The FAQ is cited daily in the newsgroup, and you should have read it
before posting.

It's a good idea to read the newsgroup and its FAQ.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/>? JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

ba...@polisource.com

unread,
Sep 18, 2006, 1:09:17 PM9/18/06
to
Dr John Stockton wrote:
> The FAQ is cited daily in the newsgroup, and you should have read it
> before posting.
>
> It's a good idea to read the newsgroup and its FAQ.

I access this group through Google Groups and didn't see anything about
a FAQ, though I didn't read any posts. Just now I looked at the second
page of post titles and I saw " FAQ Topic - How do I modify the current
browser window?" I wouldn't have clicked that if I saw it before. When
I post to a newsgroup, I just check whether there's too much spam
before I post, and I always do my own research first if I think there's
any chance of finding the answer. I read several online Javascript
references and saw nothing like what you quoted that mentioned
threading.

Can't the Javascript developers just make a regular sleep function that
doesn't thread?

Dr John Stockton

unread,
Sep 19, 2006, 7:49:55 AM9/19/06
to
JRS: In article <1158599357....@m73g2000cwd.googlegroups.com>,
dated Mon, 18 Sep 2006 10:09:17 remote, seen in
news:comp.lang.javascript, ba...@polisource.com posted :

>Dr John Stockton wrote:
>> The FAQ is cited daily in the newsgroup, and you should have read it
>> before posting.
>>
>> It's a good idea to read the newsgroup and its FAQ.
>
>I access this group through Google Groups and didn't see anything about
>a FAQ, though I didn't read any posts.

You are naive and rude. A normal person does not, in outside life,
contribute to a discussion without listening for a while first. Looking
at Subjects is inadequate.

> Just now I looked at the second
>page of post titles and I saw " FAQ Topic - How do I modify the current
>browser window?" I wouldn't have clicked that if I saw it before. When
>I post to a newsgroup, I just check whether there's too much spam
>before I post, and I always do my own research first if I think there's
>any chance of finding the answer.

Your research must have been sadly limited if you have not come across
the concept of "FAQ" before - perhaps this is your first venture into
technical newsgroups.

> I read several online Javascript
>references and saw nothing like what you quoted that mentioned
>threading.

Perhaps you do not understand the distinction between an authoritative
reference and an amateurish effort?

>Can't the Javascript developers just make a regular sleep function that
>doesn't thread?

Of course they can. But it would be entirely unnecessary. If you want
an efficient delay, just call setTimeout when the present thread is
finished, and give it the new code; adapt your mode of thinking to the
environment.

If you want an inefficient machine-hogging one, just write a trivial
wait-loop using new Date(), such as
for (D = +new Date()+3000 ; +new Date() < D ; ) ; // Delay(3000)
but don't be so silly as to put it on a Web page.

It's a good idea to read the newsgroup and its FAQ.

ba...@polisource.com

unread,
Sep 19, 2006, 8:14:10 PM9/19/06
to
Dr John Stockton wrote:
> You are naive and rude. A normal person does not, in outside life,
> contribute to a discussion without listening for a while first. Looking
> at Subjects is inadequate.

You're the one who's naive and rude. In addition, despite your
expertise, this newsgroup would be better off without you. I appreciate
the help of someone knowledgeable just like everyone else, but not if
it means allowing someone as rude as you to get an ego boost from it
and help publicize his website in his signature. I'd rather put in the
extra effort to find a solution from another source or another member
of the newsgroup than to have myself and others have to deal with
people with sticks up their ass like you. Nobody "in outside life" who
makes comments like yours should expect to get far in a civilized
society unless they have a lot of money. If you don't change your
manner, you better hope that whatever clique is putting up with your
crap never goes away.


Dr John Stockton wrote:
> Your research must have been sadly limited if you have not come across
> the concept of "FAQ" before - perhaps this is your first venture into
> technical newsgroups.

...


> Perhaps you do not understand the distinction between an authoritative
> reference and an amateurish effort?

My research included many carefully formed search engine queries and
visits to popular Javascript webpages that I've bookmarked over the
years. In a prior post to this thread (
http://groups.google.com/group/comp.lang.javascript/msg/582346180439e99e
) I said "I received a response from TheBearMay at
http://www.webdeveloper.com/forum/showthread.php?p=637609 that
clarified things for me." If you read the response, you'll see that
TheBearMay (a Super Moderator) informed me about the threads used in
setTimeout and recommended three webpages for additional reading on the
topic, some of which I'd previously seen. I responded to him saying
"none of the links you provided or any of the other pages I've read say
anything like that." With all the research I did and all the pages
specifically on setTimeout that I read, I'm right to complain about the
lack of decent online documentation for Javascript. I had noticed this
for years.


Dr John Stockton wrote:
> Your research must have been sadly limited if you have not come across
> the concept of "FAQ" before - perhaps this is your first venture into
> technical newsgroups.

Perhaps you should stop assuming things that you have no way of
knowing, especially when it takes the form of an insult. The reason I
wouldn't have clicked "FAQ Topic - How do I modify the current browser
window?" if I had looked that far down the subject titles is...and I
thought this was obvious...because the title clearly has nothing to do
with my question. As I said, "I access this group through Google Groups


and didn't see anything about

a FAQ."

The subject of this newsgroup and of the posts makes it obvious that my
question was appropriate, especially after the effort I took to find
the answer. I guess you feel I should have concentrated that effort on
this newsgroup. It's true that in that case I might have come across
your signature with the link to your FAQ in which the answer I sought
is buried. I hope it doesn't offend you that I searched a wider data
set than that. No, actually I hope you are offended.


> >Can't the Javascript developers just make a regular sleep function that
> >doesn't thread?
>
> Of course they can. But it would be entirely unnecessary. If you want
> an efficient delay, just call setTimeout when the present thread is
> finished, and give it the new code; adapt your mode of thinking to the
> environment.

As someone mentioned earlier in this thread, "The second option (and,


if I'm correct that you've place the timeout in a
loop then probably the easier one for you) is to stagger the timeouts."

Yes, much easier. I wrote my script in the most intuitive way for me,
and I would have appreciated a plain old delay with no threading and
not having to figure out how to adapt my code. Increasing the delay by
the amount of the original delay for each iteration isn't such an
obvious solution even if you know about the threading. KISS.


> If you want an inefficient machine-hogging one, just write a trivial
> wait-loop using new Date(), such as
> for (D = +new Date()+3000 ; +new Date() < D ; ) ; // Delay(3000)

No thanks.


> It's a good idea to read the newsgroup and its FAQ.

You never told me where this FAQ exists. You mean the link in your
signature?

Feel free to consider all question rhetorical and not to respond.

Dr John Stockton

unread,
Sep 20, 2006, 4:45:53 PM9/20/06
to
JRS: In article <1158711250.6...@e3g2000cwe.googlegroups.com>,
dated Tue, 19 Sep 2006 17:14:10 remote, seen in
news:comp.lang.javascript, ba...@polisource.com posted :

> ...


>and help publicize his website in his signature.

> ...

And why not? IMHO, the site is useful only if people read it, and for
that they need to know that it exists. But perhaps you think that I get
financial gain from people reading it? If so, you have a very sordidly
mercenary attitude.

>> It's a good idea to read the newsgroup and its FAQ.
>
>You never told me where this FAQ exists. You mean the link in your
>signature?

I require, but fortunately do not presume, a modicum of intelligence in
my readers.

You are a windbag.

It's a good idea to read the newsgroup and its FAQ.

Message has been deleted

ba...@polisource.com

unread,
Sep 20, 2006, 8:33:04 PM9/20/06
to
Dr John Stockton wrote:
> JRS: In article <1158711250.6...@e3g2000cwe.googlegroups.com>,
> dated Tue, 19 Sep 2006 17:14:10 remote, seen in
> news:comp.lang.javascript, ba...@polisource.com posted :
>
> > ...
> >and help publicize his website in his signature.
> > ...
>
> And why not? IMHO, the site is useful only if people read it, and for
> that they need to know that it exists. But perhaps you think that I get
> financial gain from people reading it? If so, you have a very sordidly
> mercenary attitude.

My sentence was, "I appreciate the help of someone knowledgeable just


like everyone else, but not if it means allowing someone as rude as you

to get an ego boost from it and help publicize his website in his
signature." I won't research whether you gain from it, but I assume you
do so I'm against it.


Dr John Stockton wrote:
> >> It's a good idea to read the newsgroup and its FAQ.
> >
> >You never told me where this FAQ exists. You mean the link in your
> >signature?
>
> I require, but fortunately do not presume, a modicum of intelligence in
> my readers.

In case you really didn't understand, you shouldn't expect newcomers to
look at people's signature ads. You never told me where the FAQ exists
or how I should have learned about it. You just attacked me for not
reading it. There's no way of knowing whether the FAQ is official by
seeing it mentioned in someone's signature along with his other ads. I
don't click every link to unsorted information that I see, especially
when I have a specific question.

Someone should give you a dishonorable revoking of your doctorate.

ba...@polisource.com

unread,
Sep 20, 2006, 9:00:21 PM9/20/06
to
Lee wrote:

> ba...@polisource.com said:
> >
> >As I said, "I access this group through Google Groups
> >and didn't see anything about
> >a FAQ."
>
> What does that mean? Does Google Group normally identify a FAQ
> for newsgroups? If so, it seems to be unreliable. As was pointed
> out, you should always scan the past week's titles in the newsgroup
> for any reference to a FAQ and follow it, even if the particular
> reference doesn't seem to refer to your particular problem.

I don't think Google normally identifies a FAQ, but it does have an
about page, which I usually read (
http://groups.google.com/group/comp.lang.javascript/about ). I think I
had good reason to believe that my question was appropriate considering
the research I'd done. I shouldn't be expected to read a FAQ to find an
answer when I'd already read pages specifically about the...method or
whatever it's called...that I was having a problem with, as well as
forum posts, etc. You have to stop and ask at some point.


> >As someone mentioned earlier in this thread, "The second option (and,
> >if I'm correct that you've place the timeout in a
> >loop then probably the easier one for you) is to stagger the timeouts."
> >Yes, much easier. I wrote my script in the most intuitive way for me,
> >and I would have appreciated a plain old delay with no threading and
> >not having to figure out how to adapt my code. Increasing the delay by
> >the amount of the original delay for each iteration isn't such an
> >obvious solution even if you know about the threading. KISS.
>

> That's probably not the simplest or most supportable way to use
> setTimeout() to do what you want to do.

Considering what I'd already written, my coding style, and what two or
three people told me, it probably was the simplest in my case, but I'd
probably look into more standard solutions if I intended to do much
Javascript development in the future. I'm more of a server-side person
because it's easier to protect code and you have more powerful
languages to choose from.


> See http://www.jibbering.com/faq/#FAQ4_20
>
> Web browsers are event-driven systems. Event-driven systems should
> never sleep. Providing setTimeout() and setInterval() instead of
> any sort of sleep() was a well-considered design decision.

There's no real reasoning there. It seems like setTimeout does what
sleep does. I guess it shortens execution time in some cases because it
doesn't wait around for stuff it's not explicitly told to delay. I
think it should be the programmer's responsibility to decide when
sleep() is appropriate. No big deal though because I'm not sure. I just
wish the documentation was better. I still don't know where to look for
the best Javascript documentation.

Randy Webb

unread,
Sep 20, 2006, 11:16:44 PM9/20/06
to
Dr John Stockton said the following on 9/20/2006 4:45 PM:

<snip>

> You are a windbag.

And you are an idiot.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/

ba...@polisource.com

unread,
Sep 20, 2006, 11:25:46 PM9/20/06
to

Interesting reasoning.

Message has been deleted

Randy Webb

unread,
Sep 21, 2006, 1:49:36 AM9/21/06
to
ba...@polisource.com said the following on 9/20/2006 11:25 PM:

> Randy Webb wrote:
>> Dr John Stockton said the following on 9/20/2006 4:45 PM:
>>
>> <snip>
>>
>>> You are a windbag.
>> And you are an idiot.
>>
> Interesting reasoning.

Not interesting, it's the result of putting up with his pedantic
bullshit for almost 10 years now and realizing that he truly is an idiot
in the original sense of the word.

ba...@polisource.com

unread,
Sep 21, 2006, 1:56:49 AM9/21/06
to
Lee wrote:

> >It seems like setTimeout does what
> >sleep does.
>

> Not remotely. setTimeout() doesn't pause execution of anything.
> It simply adds a statement to an event queue to be executed after
> a specified amount of time has passed.

I meant that I thought it does everything sleep does _plus_ it allows
the script to continue, assuming there's anything else for the script
to do. If there's nothing else for the script to do, I figured it
functions as sleep() does, so I wasn't sure "Event-driven systems
should never sleep" was accurate. But, now I see:

> In the meantime, other
> Javascript can continue to run and the browser is still able to
> respond to button clicks, etc, which would not be the case if
> sleep() were used.
...
> Javascript is very commonly used by people who aren't software
> professionals and who don't bother to read the documentation.
> If a sleep() function was available, many of them would use it,
> resulting in users disabling Javascript in order to maintain
> control over their browsers.

I thought sleep() allows other things to happen that aren't in the
script. Do-nothing loops are the types of delays that cause problems.
What I wanted was a sleep() that wouldn't start a new thread and would
stop execution until the specified time elapses, but at the same time
allowed things external to that particular script to happen.

I've been thinking that the the cause of one of the problems I'm still
having with the animated version of the script in question (
http://www.polisource.com/PublicMisc/list-splitter-animation.html ) is
due to so many threads being created (or events being added to the
queue, however you say it) without waiting for the previous one to be
executed. Sleep() might eliminate that problem. For example, at the
prompts, enter 10 (columns), v (vertical), and w (webpage). If your
computer isn't really fast, the animation won't be smooth. On my
Celeron, 2.1 GH with 640 MB RAM, there's a long pause and you miss some
of the movement, but after 30 seconds everything appears in its proper
position. Entering different parameters might show bugs unrelated to
the jumpiness so I've been telling people to use 10, v, w.

ba...@polisource.com

unread,
Sep 21, 2006, 2:05:45 AM9/21/06
to
Randy Webb wrote:
> ba...@polisource.com said the following on 9/20/2006 11:25 PM:
> > Randy Webb wrote:

> Not interesting, it's the result of putting up with his pedantic
> bullshit for almost 10 years now and realizing that he truly is an idiot
> in the original sense of the word.

Oh, I actually thought you were calling me an idiot. My experience with
the Perl community made me jump to conclusions. I was beginning to
wonder if I should just stay away from web technology communities all
together.

Randy Webb

unread,
Sep 21, 2006, 2:52:30 AM9/21/06
to
ba...@polisource.com said the following on 9/21/2006 2:05 AM:

> Randy Webb wrote:
>> ba...@polisource.com said the following on 9/20/2006 11:25 PM:
>>> Randy Webb wrote:
>
>> Not interesting, it's the result of putting up with his pedantic
>> bullshit for almost 10 years now and realizing that he truly is an idiot
>> in the original sense of the word.
>
> Oh, I actually thought you were calling me an idiot.

Nah, I save those terms for people who deserve to be called an idiot :)

> My experience with the Perl community made me jump to conclusions.

What you are going to find in this group (and any technical group in
general) are the people who stick to some standard and thats it, people
who think they know it all, those who know a lot but know they don't
know it all, and some who just don't know there head from a hole in the
ground (some fit multiple categories). You just have to stick around
this group long enough (or read enough of the archives) to know which
are which.

Everybody has there moments (I do) but JRS seems to have them daily for
23 1/2 hours at the time.

> I was beginning to wonder if I should just stay away from web technology
> communities all together.

And miss out on all this fun?!?!?!

0 new messages