473,761 Members | 8,372 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Efficient use of setTimeout ?

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(docume nt.getElementBy Id("speed").val ue);
var Interval = parseInt(docume nt.getElementBy Id("interval"). value);
var CurrentPoint = timeline.getCen terLatLng();
var NewLng = CurrentPoint.x + (HourConst*Inte rval);
if (NewLng > 180) NewLng = -180;
timeline.recent erOrPanToLatLng (new GPoint(NewLng , 0));
if (Playing) PlayTimer = window.setTimeo ut("PlayTimelin e()",Speed);
}

Here is the code for the buttons:
<a href="#" id="Stop" onclick="Playin g = false;
window.clearTim eout(PlayTimer) ; return false;">...
<a href="#" id="Play" onclick="Playin g = 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

Mar 3 '06 #1
3 8594
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(docume nt.getElementBy Id("speed").val ue);
3rd recommendation: always define the radix when using parseInt:

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

http://devedge-temp.mozilla.org/libr...s.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(docume nt.getElementBy Id("interval"). value);
var CurrentPoint = timeline.getCen terLatLng();
var NewLng = CurrentPoint.x + (HourConst*Inte rval);
if (NewLng > 180) NewLng = -180;
timeline.recent erOrPanToLatLng (new GPoint(NewLng , 0));
if (Playing) PlayTimer = window.setTimeo ut("PlayTimelin e()",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="Playin g = false;
window.clearTim eout(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="Playin g = false;
clearTimeout(Pl ayTimer); PlayTimer = null;">Stop</button>
<a href="#" id="Play" onclick="Playin g = 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
--
remove blah to email me
Mar 3 '06 #2
Gérard Talbot wrote:
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="Playin g = false;
clearTimeout(Pl ayTimer); 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

Mar 3 '06 #3
jshanman wrote :
Gérard Talbot wrote:
1st recommendation: never set y < 32 . Otherwise people with modest
system will crash.
I wouldn't set it to anything below 250ms


A good decision then!
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".


(after checking a bit more your code,..) Your code does that already:
addEventListene r 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.
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?


Regarding setTimeout
"Speaking of animation, one of the most common techniques for animating
elements is to use a timer with window.setTimeo ut 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.setTimeo ut() 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/de...l/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.
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 : )


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.
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="Playin g = false;
clearTimeout(Pl ayTimer); 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?


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.
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...

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.

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?


You can use the general-purpose and cross-browser function
function ChangingElement Text (Id_Attribute_V alue, newText)
I proposed at this precise url:

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

or (best, IMO) you can use
objRef.childNod es[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/...NodeValue.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/...acterData.html

Gérard
--
remove blah to email me
Mar 3 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
3067
by: Jupiter49 | last post by:
I'm trying to move pictures around on the screen, with a slight delay between the first picture and second picture (following onmousemove). When I add the setTimeout function I must be doing it wrong because the function that calculates the new coordinates for the picture returns 32 million and change instead of the coordinate. This causes the picture to not be able to appear on the display, obviously. Here's the calling code (snipped...
6
2253
by: Brent | last post by:
Is there any obvious reason why there's no delay in the execution of setting the id.style.display when this function gets called? function Hide(divId,timeout) { var id = document.getElementById(divId); setTimeout(id.style.display = 'none',timeout); } Thanks for any help.
12
5555
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. Foo = function(type) { this.num = 0; this.type = type this.trigger(); } Foo.prototype.trigger = function() {
28
5308
by: Andre | last post by:
Hi, Does anyone know whether the ECMA, or an other standard document, specifies a maximum for the value that can be pass to the setTimeOut() function in Javascript? Andre
4
5234
by: E | last post by:
I am having trouble with setTimeout working on a second call to the setTimeout function from a second page which is an html page. Here is the scenario. I have a web page and onload it calls a javascript function which calls setTimeout and will process a second javascript function "Warn" just before the session expires. The Warn function displays an html page with a button. A second timer is started to cause the html page to close...
6
10921
by: Max | last post by:
Hi, I'm not exactly sure why this doesn't work. I'm basically just trying a simple approach at a slide down div. function slide_div { setTimeout("document.getElementById('mydiv').style.length='10px';",1000);
15
3796
by: nikki_herring | last post by:
I am using setTimeout( ) to continuously call a function that randomly rotates/displays 2 images on a page. The part I need help with is the second image should rotate 3 seconds after the first image rotates. I cannot figure out how to accomplish the 3 second delay. My code is pasted below: function randPic(){ randPic1(); randPic2();
7
2415
by: Martin | last post by:
Can I have two setTimeouts running at the same time - with two different intervals? I want to start one timer and, before it times out, start another one I've tried this and they seems to interfer with one another.
6
5011
by: Steve | last post by:
I have noticed that setTimeout works if the brackets () are left off the function called, like this: window.setTimeout(myFunction, 1000); I thought that the brackets were required to show that myFunction is a function, so why are they not required here? Also I have found that if I want to pass a value to a function with setTimeout I need to enclose the function in inverted commas, like
0
9531
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9345
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10115
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9957
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9905
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7332
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5229
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5373
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3881
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.