Efficient use of setTimeout ?

J

jshanman

I've created a "Play" button for my timeline that uses the Google Maps
API. It basicly scrolls the timeline x interval every y milliseconds.
The problem is the browser responds slowly even after the "Stop" button
is clicked. (it responds slowly while playing, but thats to be
expected with everything that it is doing)

How can I get the browser back to it's more responsive state after the
timeout is cleared?

Here is the function that calls the timeout:
function PlayTimeline() {
var Speed = parseInt(document.getElementById("speed").value);
var Interval = parseInt(document.getElementById("interval").value);
var CurrentPoint = timeline.getCenterLatLng();
var NewLng = CurrentPoint.x + (HourConst*Interval);
if (NewLng > 180) NewLng = -180;
timeline.recenterOrPanToLatLng(new GPoint(NewLng , 0));
if (Playing) PlayTimer = window.setTimeout("PlayTimeline()",Speed);
}

Here is the code for the buttons:
<a href="#" id="Stop" onclick="Playing = false;
window.clearTimeout(PlayTimer); return false;">...
<a href="#" id="Play" onclick="Playing = true; PlayTimeline(); return
false;">...

Source Page:
http://www.endeavorpub.com/wiki/mapd.php (this is the development page)

What can I do to make this more efficient (besides not doing it)

- JS
http://www.endeavorpub.com
 
G

Gérard Talbot

jshanman wrote :
I've created a "Play" button for my timeline that uses the Google Maps
API. It basicly scrolls the timeline x interval every y milliseconds.

1st recommendation: never set y < 32 . Otherwise people with modest
system will crash.

2nd recommendation: use a proper event listener, not an interval. The
script will be triggered on that event, not all the time. It makes a lot
more sense.
Addendum: the script is that start autoscroll timeline, right? Then you
may consider something else, a better alternative... pretty sure there
could be something better. You definitively need to fix your markup code
and CSS code before going over optimization of javascript/DHTML.
The problem is the browser responds slowly even after the "Stop" button
is clicked.

It doesn't respond slowly: it can't respond (overload, over-burdened),
it can not cope with the script demand. Again, consider 1st and 2nd
recommendations.

(it responds slowly while playing, but thats to be
expected with everything that it is doing)

How can I get the browser back to it's more responsive state after the
timeout is cleared?

Here is the function that calls the timeout:
function PlayTimeline() {
var Speed = parseInt(document.getElementById("speed").value);

3rd recommendation: always define the radix when using parseInt:

http://jibbering.com/faq/#FAQ4_12

http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.5/guide/fcns.html#1008379

If I understand your code (I may not have all of the necessary chunk of
code to assess this properly), the user defines the speed, right?
var Interval = parseInt(document.getElementById("interval").value);
var CurrentPoint = timeline.getCenterLatLng();
var NewLng = CurrentPoint.x + (HourConst*Interval);
if (NewLng > 180) NewLng = -180;
timeline.recenterOrPanToLatLng(new GPoint(NewLng , 0));
if (Playing) PlayTimer = window.setTimeout("PlayTimeline()",Speed);

I congratulate you on using meaningful, intuitive, self-explanatory
variable identifiers. This is good for debugging and for reviewing by
others who may not know what your code do or is about.
}

Here is the code for the buttons:
<a href="#" id="Stop" onclick="Playing = false;
window.clearTimeout(PlayTimer); return false;">...

4th recommendation: use a button since this is a command; do not use a
pseudo-link (a link) since the link goes nowhere. Avoid href="#"
everywhere.

<button type="button" id="btnStop" onclick="Playing = false;
clearTimeout(PlayTimer); PlayTimer = null;">Stop said:
<a href="#" id="Play" onclick="Playing = true; PlayTimeline(); return
false;">...

Source Page:
http://www.endeavorpub.com/wiki/mapd.php (this is the development page)

5th recommendation: Absolutely and positively consider to validate your
markup code and CSS code and to use a strict DTD: the page has 284
markup errors and the page takes well over 40 seconds to load on a
dialup connection.

6th recommendation: avoid innerHTML when dynamically setting the node
value of a text node. innerHTML is relatively slow and system resource
demanding.
What can I do to make this more efficient (besides not doing it)

- JS
http://www.endeavorpub.com

Gérard
 
J

jshanman

Gérard Talbot said:
1st recommendation: never set y < 32 . Otherwise people with modest
system will crash.

I wouldn't set it to anything below 250ms
2nd recommendation: use a proper event listener, not an interval. The
script will be triggered on that event, not all the time. It makes a lot
more sense.

Can you give me a simple exampe of a "proper event listener".

I am considering just placing the next setTimeout at the end of the
function that re-draws the labels in the timeline, that way, it won't
try to move the timeline again until it has completly finished
moving/drawing it the first time.
Addendum: the script is that start autoscroll timeline, right? Then you
may consider something else, a better alternative... pretty sure there
could be something better.

An alternative as in something other then the Google Maps API for the
timeline? Or what? I've considered writing my own interface for the
timeline but I will just be re-writing basicly the same code, just
minus all the lat/long stuff.
You definitively need to fix your markup code
and CSS code before going over optimization of javascript/DHTML.

I know, I know, I'll get to that before I put the application in beta
status : )
It doesn't respond slowly: it can't respond (overload, over-burdened),
it can not cope with the script demand. Again, consider 1st and 2nd
recommendations.

3rd recommendation: always define the radix when using parseInt:

The values that go into those parseInt come from a select, so I define
the only values that they can be. But I will do as you suggest by
putting a ", 10" in the statement.
I congratulate you on using meaningful, intuitive, self-explanatory
variable identifiers. This is good for debugging and for reviewing by
others who may not know what your code do or is about.

With all the javascript on that page, I would be lost the day after I
programmed something if I didn't do that...
4th recommendation: use a button since this is a command; do not use a
pseudo-link (a link) since the link goes nowhere. Avoid href="#"
everywhere.

<button type="button" id="btnStop" onclick="Playing = false;
clearTimeout(PlayTimer); PlayTimer = null;">Stop</button>

Just out of curiousity, why should it be avoided? Are there browser
issues with that, or is it just best practice? The only reason I've
avoided buttons this far is because they take up more pixel space the
just text links.
5th recommendation: Absolutely and positively consider to validate your
markup code and CSS code and to use a strict DTD: the page has 284
markup errors and the page takes well over 40 seconds to load on a
dialup connection.

I don't know if I will use a Strict DTD, but I will validate once I get
the bulk of the program working. I already know this application isn't
going to be very dialup friendly...
6th recommendation: avoid innerHTML when dynamically setting the node
value of a text node. innerHTML is relatively slow and system resource
demanding.

As opposed to ??
I have lots of innerHTML... What would you recommend I use instead?

Thank you for taking the time to look over all this. I appreciate it!

- JS
http://www.endeavorpub.com
 
G

Gérard Talbot

jshanman wrote :
I wouldn't set it to anything below 250ms

A good decision then!
Can you give me a simple exampe of a "proper event listener".

(after checking a bit more your code,..) Your code does that already:
addEventListener is doing it.

[objectReference].on[eventtype] = functionName;
is the general syntax for non DOM2 event browsers.

I am considering just placing the next setTimeout at the end of the
function that re-draws the labels in the timeline, that way, it won't
try to move the timeline again until it has completly finished
moving/drawing it the first time.


An alternative as in something other then the Google Maps API for the
timeline? Or what?

Regarding setTimeout
"Speaking of animation, one of the most common techniques for animating
elements is to use a timer with window.setTimeout to position an element
on the page incrementally. A quick tip: **Use as few timers as
possible.** Timers consume valuable system resources, and the behavior
of multiple timers, all working together, will greatly vary on
differently powered machines. A way to animate multiple elements, while
minimizing timer use, is to employ a single main loop, powered with a
single window.setTimeout() call. In that single loop, keep a list of all
elements you need to manipulate. Loop through that list with each tick,
and perform your required move."

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndude/html/dude1201.asp


I've considered writing my own interface for the
timeline but I will just be re-writing basicly the same code, just
minus all the lat/long stuff.

I examined your page code some more: it would take me quite a lot of
time to understand all of its internal logic, intricated calls and
inter-dependent functions. I could do it but it would take me quite some
time.

Mozilla-based browsers still have performance problems with some DHTML
redrawing a page (like moving objects, needing to be redrawed). There
are ways to avoid such performance problems. But the browser is still a
bit more sensitive to DHTML performance than, say, MSIE 6.
I know, I know, I'll get to that before I put the application in beta
status : )

This is not the normal order of developing a page then. You should first
develop the content, then its structure, then the markup code (and
accessibility), then the style info and then, only then, the script:
that's the best way to develop a webpage, even a very intensely
dynamic/javascript one.
The values that go into those parseInt come from a select, so I define
the only values that they can be. But I will do as you suggest by
putting a ", 10" in the statement.


With all the javascript on that page, I would be lost the day after I
programmed something if I didn't do that...


Just out of curiousity, why should it be avoided? Are there browser
issues with that, or is it just best practice?

Best practice for many reasons:
- if javascript support is disabled or inexistent, then the link remains
functional when a link is used; <a href="#" ...> is always a mistake, is
always a webpage design mistake.
- search indexing engines won't waste time with a <button> but will
index for wrong reasons an <a href="#" ...>
- mouse gestures, accessibility applications, etc.. won't waste
time/confuse users/frustrate with <button> but will with <a href="#" ...>
- a link is a link and should be a link and load a referenced resource
into the same webpage otherwise you're misusing markup semantic;
therefore, a link will behave as expected and as a link in other media
and other web-aware applications... which may not be a visual browser
- etc.

The only reason I've
avoided buttons this far is because they take up more pixel space the
just text links.


I don't know if I will use a Strict DTD, but I will validate once I get
the bulk of the program working. I already know this application isn't
going to be very dialup friendly...


Maybe the nr 1 problem you have is non-optimized javascript right now;
but you first should start with/be addressing the markup code, then CSS
code and then address the javascript code. In that order.
The goal is to have a page like yours to be loading itself faster; your
webpage should not take so loong to load. The page should load very fast
if javascript is disabled.

As opposed to ??
I have lots of innerHTML... What would you recommend I use instead?

You can use the general-purpose and cross-browser function
function ChangingElementText (Id_Attribute_Value, newText)
I proposed at this precise url:

https://bugzilla.mozilla.org/show_bug.cgi?id=74952#c120

or (best, IMO) you can use
objRef.childNodes[x].nodeValue = strNewText;
where x is the indexth textnode you want to change for non-DOM3
compliant browsers and then use textContent for DOM3 compliant browsers.
Opera 9 and Mozilla 1.5+ (Firefox 1.x, NS 7.x) all support textContent.

So, first check for object support of textContent, else, use
childNodes[x].nodeValue = strNewText

innerHTML versus nodeValue performance comparison
http://www.gtalbot.org/DHTMLSection/innerHTMLvsNodeValue.html

There is even an article explaining/demonstrating that recourse to
innerHTML is slower for changing a textnode at msdn.

If you know well what you want to change, then you can safely rely onto
DOM2 CharacterData methods which are all supported by MSIE 6, MSIE 5.x
(except 1), Opera 7+, Firefox 1.x, Mozilla 1.x, Safari 1.2+, etc.:

DOM level 2 CharacterData Interface tests
http://www.gtalbot.org/DHTMLSection/DOM2CharacterData.html

Gérard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,278
Latest member
BuzzDefenderpro

Latest Threads

Top