Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > setTimeOut

Reply
Thread Tools

setTimeOut

 
 
Richard Cornford
Guest
Posts: n/a
 
      09-25-2004
Michael Winter wrote:
> Yann-Erwan Perio wrote:

<snip>
>>> It seems hack-ish, though. But it does work.

>>
>> No no no, it's not hackish, that's just how javascript can
>> be written, and most of the time, should be written (IMHO).

>
> The original just seemed cleaner. Self-contained.


As stated, when setTimeout/Interval are using sting arguments they have
no choice but evaluate the string in the global context. So 'self
contained' isn't necessarily achievable. But, loosing the integrity of
the original anonymous function might be done in a way that made it
dependent only on another unit that was itself self contained, and
potentially re-usable.

My inclination now is to pass execution-shedding tasks off to distinct
components (that can handle these details themselves internally), but
that development came out of re-usable toString functions such as:-

var funcCallingToString = (function(){
var fncId = '__f';
var fnRfs = {};
function actualToString(){
var fId;
while(fnRfs[fncId]){
fncId = fncId + 'Q';
}
fnRfs[fncId] = this; //this - is the function object as toSting
//is called as a method of the fucntion
fId = fncId;
this.toString = function(){
return ('funcCallingToString.fr.'+fId+'()');
}
return this.toString();
}
actualToString.fr = fnRfs;
return actualToString;
})();

- where the facility to reference the function globally is created as
needed for any function with which the above is used as a toString
method. (It has the drawback of creating an object full of references to
what would be expected to be inner functions and so would inhibit
garbage collection and the destruction of closures that had done their
job. That problem could be mitigated to some extent by implementing a
finalize/destroy mechanism, but it was facilitating that (and the more
efficient removal of spent inner function references) that made me think
that scheduling should itself be a task for more (internally) elaborate
self-contained components.)

However, using it with your original code might go:-

window.onload = function() {
var i = document.images['cassini'],
j = 0,
p = ['one', 'two', 'three', 'four', 'five', 'six', 'seven',
'eight'],
n = p.length;

function flip() {
i.src = 'images/' + p[j] + '.jpg';
j = (j + 1) % n;
}
flip.toString = funcCallingToString;

setInterval(flip, 1000);
};

- and the same - toString - function would also be available to any
other functions needing the setTimeout/Interval fallback.

Richard.


 
Reply With Quote
 
 
 
 
Frances Del Rio
Guest
Posts: n/a
 
      09-25-2004


Michael Winter wrote:

[. . . .]

>> var photos = new
>> Array("one","two","three","four","five","six","sev en","eight")

>
>
> Define arrays with literals:
>
> var photos = ['one', 'two', 'three', 'four', 'five', 'six',
> 'seven', 'eight'];


please, what is difference between these two ways of declaring arrays??

a) mine: var photos = new
Array("one","two","three","four","five","six","sev en","eight")

yours: var photos = ['one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight'];

thank you very much for yr help.. Frances



 
Reply With Quote
 
 
 
 
Frances Del Rio
Guest
Posts: n/a
 
      09-25-2004


Michael Winter wrote:

[. . . . . ]

>
> var j = 0,
> photos = ['one', 'two', 'three', 'four', 'five', 'six',
> 'seven', 'eight'];
>
> function flip() {
> document.images['cassini'].src = 'images/' + photos[j] + '.jpg';
> j = (j + 1) % photos.length;
> }
> // Call onload:
> setInterval(flip, 1000);
>
> This is a simple version of what you want to achieve. setInterval will
> call flip approximately every second. When it does, the first statement
> will change the source of the IMG element, cassini, and increment the
> index variable, j. The modulus (%) ensures that the value of j stays
> within the range 0 <= j < 8.
>
> However, this code pollutes the global namespace. It also looks-up a
> reference to the IMG, cassini, and the length property of the photos
> array on every invocation of flip.
>
> window.onload = function() {
> var i = document.images['cassini'],
> j = 0,
> p = ['one', 'two', 'three', 'four', 'five', 'six', 'seven',
> 'eight'],
> n = p.length;
>
> function flip() {
> i.src = 'images/' + p[j] + '.jpg';
> j = (j + 1) % n;
> }
> flip.toString = function() {return 'flip()';};
>
> setInterval(flip, 1000);
> };
>
> That's quite a transformation.
>
> The first thing to note is the external function expression, function()
> { ... }. You can think of this just like any other function, except it
> doesn't have a name. What this does is produce a new scope level. As
> with all functions, the local variables declared here aren't accessible
> outside of the function. This means you can name variables, that would
> normally be global, anything you like and not worry about them clashing
> with other variables.
>
> Inside the function, things are much like they were last time, with two
> slight differences:
>
> 1) A reference to the IMG element, cassini, has been assigned to the
> variable, i. This allows it to be looked-up once only, rather than
> repeatedly.
> 2) Similarly, the length property of the array of filenames has been
> stored in n. Like the reference to cassini, it doesn't change, so why
> keep looking it up?
>
> There's a third difference, which follows after the declaration of
> flip. All functions and objects have a method called toString. Whenever
> a string value is required, and an object or function is given, this
> method is called and string that represents that object is returned[1].
> The setInterval function, like setTimeout, can accept two types as its
> first argument. A function reference, and a string. Older browsers only
> accept a string. Giving the function, flip, a toString method means
> that browsers can convert the argument to a form they can use.


Michael, thank you very very much for all your help.. I have just spent
about an hour studying and dissecting your post.. and got the two
sripts you gave me to work...

http://www.francesdelrio.com/cassini/index_rolls.html
http://www.francesdelrio.com/cassini...er-script.html

(the first one -- the not-so-good script that u said...) takes longer to
load.. (again, as I mentioned in an earlier post, my stuff loads a bit
slow anyway b/c I'm being hosted abroad (in Chile..) by a friend, he's
hosting me for free, and their int'l traffic is slower... these two
scripts work perfectly locally, start running immediately; but on-line
imgs take a bit to load..)

I have two small questions:

1) is this
window.onload = function()

the same as calling function in onload event handler in body tag?

2) you have commas after the var declarations, I had never seen that..

var i = document.images['cassini'],
j = 0,

of course have larger questions too.. still don't understand everything
about this script, but at least now I have one that works so have
something to study this with.. and re-digest everything you wrote..
again, thank you very much.. Frances












 
Reply With Quote
 
Frances Del Rio
Guest
Posts: n/a
 
      09-25-2004
ok Michael, made images smaller, now they should load faster..

http://www.francesdelrio.com/cassini/index_rolls.html
http://www.francesdelrio.com/cassini...er-script.html

again, many many thanks for your help... Frances


Frances Del Rio wrote:

>
>
> Michael Winter wrote:
>
> [. . . . . ]
>
>>
>> var j = 0,
>> photos = ['one', 'two', 'three', 'four', 'five', 'six',
>> 'seven', 'eight'];
>>
>> function flip() {
>> document.images['cassini'].src = 'images/' + photos[j] + '.jpg';
>> j = (j + 1) % photos.length;
>> }
>> // Call onload:
>> setInterval(flip, 1000);
>>
>> This is a simple version of what you want to achieve. setInterval
>> will call flip approximately every second. When it does, the first
>> statement will change the source of the IMG element, cassini, and
>> increment the index variable, j. The modulus (%) ensures that the
>> value of j stays within the range 0 <= j < 8.
>>
>> However, this code pollutes the global namespace. It also looks-up a
>> reference to the IMG, cassini, and the length property of the photos
>> array on every invocation of flip.
>>
>> window.onload = function() {
>> var i = document.images['cassini'],
>> j = 0,
>> p = ['one', 'two', 'three', 'four', 'five', 'six', 'seven',
>> 'eight'],
>> n = p.length;
>>
>> function flip() {
>> i.src = 'images/' + p[j] + '.jpg';
>> j = (j + 1) % n;
>> }
>> flip.toString = function() {return 'flip()';};
>>
>> setInterval(flip, 1000);
>> };
>>
>> That's quite a transformation.
>>
>> The first thing to note is the external function expression,
>> function() { ... }. You can think of this just like any other
>> function, except it doesn't have a name. What this does is produce a
>> new scope level. As with all functions, the local variables declared
>> here aren't accessible outside of the function. This means you can
>> name variables, that would normally be global, anything you like and
>> not worry about them clashing with other variables.
>>
>> Inside the function, things are much like they were last time, with
>> two slight differences:
>>
>> 1) A reference to the IMG element, cassini, has been assigned to the
>> variable, i. This allows it to be looked-up once only, rather than
>> repeatedly.
>> 2) Similarly, the length property of the array of filenames has been
>> stored in n. Like the reference to cassini, it doesn't change, so why
>> keep looking it up?
>>
>> There's a third difference, which follows after the declaration of
>> flip. All functions and objects have a method called toString.
>> Whenever a string value is required, and an object or function is
>> given, this method is called and string that represents that object
>> is returned[1]. The setInterval function, like setTimeout, can accept
>> two types as its first argument. A function reference, and a string.
>> Older browsers only accept a string. Giving the function, flip, a
>> toString method means that browsers can convert the argument to a
>> form they can use.

>
>
> Michael, thank you very very much for all your help.. I have just spent
> about an hour studying and dissecting your post.. and got the two
> sripts you gave me to work...
>
> http://www.francesdelrio.com/cassini/index_rolls.html
> http://www.francesdelrio.com/cassini...er-script.html
>
> (the first one -- the not-so-good script that u said...) takes longer to
> load.. (again, as I mentioned in an earlier post, my stuff loads a bit
> slow anyway b/c I'm being hosted abroad (in Chile..) by a friend, he's
> hosting me for free, and their int'l traffic is slower... these two
> scripts work perfectly locally, start running immediately; but on-line
> imgs take a bit to load..)
>
> I have two small questions:
>
> 1) is this
> window.onload = function()
>
> the same as calling function in onload event handler in body tag?
>
> 2) you have commas after the var declarations, I had never seen that..
>
> var i = document.images['cassini'],
> j = 0,
>
> of course have larger questions too.. still don't understand everything
> about this script, but at least now I have one that works so have
> something to study this with.. and re-digest everything you wrote..
> again, thank you very much.. Frances
>
>
>
>
>
>
>
>
>
>
>
>


 
Reply With Quote
 
Frances Del Rio
Guest
Posts: n/a
 
      09-25-2004


Michael Winter wrote:


>
> var j = 0,
> photos = ['one', 'two', 'three', 'four', 'five', 'six',
> 'seven', 'eight'];
>
> function flip() {
> document.images['cassini'].src = 'images/' + photos[j] + '.jpg';
> j = (j + 1) % photos.length;
> }
> // Call onload:
> setInterval(flip, 1000);
>
> This is a simple version of what you want to achieve. setInterval will
> call flip approximately every second. When it does, the first statement
> will change the source of the IMG element, cassini, and increment the
> index variable, j. The modulus (%) ensures that the value of j stays
> within the range 0 <= j < 8.
>
> However, this code pollutes the global namespace. It also looks-up a
> reference to the IMG, cassini, and the length property of the photos
> array on every invocation of flip.
>
> window.onload = function() {
> var i = document.images['cassini'],
> j = 0,
> p = ['one', 'two', 'three', 'four', 'five', 'six', 'seven',
> 'eight'],
> n = p.length;
>
> function flip() {
> i.src = 'images/' + p[j] + '.jpg';
> j = (j + 1) % n;
> }
> flip.toString = function() {return 'flip()';};
>
> setInterval(flip, 1000);
> };


I forgot to mention.. I started this as an exercise to learn how to
implement loops w/setTimeOuts.. and yet both solutions you gave me have
no loops!! thank you again... Frances



 
Reply With Quote
 
Michael Winter
Guest
Posts: n/a
 
      09-27-2004
I'll try to answer all of your questions in this one post.

On Sat, 25 Sep 2004 14:02:13 -0400, Frances Del Rio <(E-Mail Removed)>
wrote:

> please, what is difference between these two ways of declaring
> arrays??
>a) mine: var photos = new Array("one","two","three","four","five",
> "six","seven","eight")
>yours: var photos = ['one', 'two', 'three', 'four', 'five',
> 'six', 'seven', 'eight'];


As far as the end result is concerned, none. Both produce arrays
initialised with those values. However, it's generally considered good
form to specify initialised values and objects with literals, rather than
anything else. If you want to create an array with a certain number of
uninitialised elements, then use the Array constructor with an argument
specifying that amount.


On Sat, 25 Sep 2004 15:40:12 -0400, Frances Del Rio <(E-Mail Removed)>
wrote:

> [...] these two scripts work perfectly locally, start running
> immediately; but on-line imgs take a bit to load..)


They won't start running until the document has loaded, which means that
any images must have been loaded, too.

> 1) is this
> window.onload = function()
>
> the same as calling function in onload event handler in body tag?


If you changed that function expression to just a function, yes.

function myFunction() {
// ...
}

// Don't add parentheses!
window.onload = myFunction;

is the same as

<body onload="myFunction();">

> 2) you have commas after the var declarations, I had never seen
> that..
>
> var i = document.images['cassini'],
> j = 0,


It's simply a way of declaring several variables with one var statement.
It's exactly the same as:

var i = document.images['cassini'];
var j = 0;
// etc.

I just prefer the former.

It can also be used with for statements:

for(var i = 0, n = obj.length; i < n; ++i) {

a pattern I often use.


On Sat, 25 Sep 2004 17:05:13 -0400, Frances Del Rio <(E-Mail Removed)>
wrote:

> I forgot to mention.. I started this as an exercise to learn how to
> implement loops w/setTimeOuts.. and yet both solutions you gave me have
> no loops!! thank you again... Frances


"Looping" with setTimeout, in this sense, doesn't actually involve any
kind of loop construct (for, do..while, etc) at all. It involves
setTimeout calling a function, which itself uses setTimeout to call the
same function. An example should make that clear:

function myFunction() {
// Do something periodically

setTimeout(myFunction, 2000);
}
// Start the "loop" going
myFunction();

Once myFunction is called once, the setTimeout call placed within it calls
myFunction again, two seconds later. This repeats ad infinitum.

However, a more reliable two second period can be achieved using
setInterval.

function myFunction() {
// Do something periodically
}
setInterval(myFunction, 2000);

This is because the delay with the setTimeout "loop" would actually be,
2000ms plus the time to execute the preceeding code. On a fast computer
executing little code, that might still be 2000ms, but a larger function
on a slower computer might be more obtrusive.

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
 
Reply With Quote
 
Dr John Stockton
Guest
Posts: n/a
 
      09-27-2004
JRS: In article <opsezjtq06x13kvk@atlantis>, dated Mon, 27 Sep 2004
12:30:36, seen in news:comp.lang.javascript, Michael Winter <M.Winter@bl
ueyonder.co.invalid> posted :
>"Looping" with setTimeout, in this sense, doesn't actually involve any
>kind of loop construct (for, do..while, etc) at all. It involves
>setTimeout calling a function, which itself uses setTimeout to call the
>same function. An example should make that clear:
>
> function myFunction() {
> // Do something periodically
>
> setTimeout(myFunction, 2000);
> }
> // Start the "loop" going
> myFunction();


The call to setTimeout can be placed at the beginning of myFunction. I
do not know what happens if the first myFunction has not completed
before the next is called.


>Once myFunction is called once, the setTimeout call placed within it calls
>myFunction again, two seconds later. This repeats ad infinitum.
>
>However, a more reliable two second period can be achieved using
>setInterval.
>
> function myFunction() {
> // Do something periodically
> }
> setInterval(myFunction, 2000);
>
>This is because the delay with the setTimeout "loop" would actually be,
>2000ms plus the time to execute the preceeding code. On a fast computer
>executing little code, that might still be 2000ms, but a larger function
>on a slower computer might be more obtrusive.


One must also consider the mechanism whereby Timeout or Interval is
implemented. In Win98, I find that neither is exact on the long-term
average.

See <URL:http://www.merlyn.demon.co.uk/js-date0.htm#TaI>, using a
variety of computer types, operating systems and browsers - and someone
let me know what happens!

--
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.
 
Reply With Quote
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      10-10-2004
Frances Del Rio wrote:

> Michael Winter wrote:
>>> var photos = new
>>> Array("one","two","three","four","five","six","sev en","eight")

>>
>> Define arrays with literals:
>>
>> var photos = ['one', 'two', 'three', 'four', 'five', 'six',
>> 'seven', 'eight'];

>
> please, what is difference between these two ways of declaring arrays??


The second one (the Array initializer) requires at least JavaScript 1.1
and/or an ECMAScript 3 compliant language implementation. (The different
quote character does not matter.)


HTH

PointedEars
--
Twice as good as a can of Raid!
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
javascript setTimeout does not work =?Utf-8?B?RQ==?= ASP .Net 4 05-02-2006 08:21 PM
setTimeout JR HTML 3 04-15-2004 12:07 PM
settimeout j van c HTML 5 12-07-2003 09:08 AM
socket settimeout ? Colin Brown Python 0 12-03-2003 12:28 AM
Smart navigation and js setTimeout Andy Pickering ASP .Net 1 10-27-2003 10:51 AM



Advertisments