Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Javascript (http://www.velocityreviews.com/forums/f68-javascript.html)
-   -   setTimeout and an object's methods (http://www.velocityreviews.com/forums/t923364-settimeout-and-an-objects-methods.html)

Andrew Poulos 03-05-2006 07:41 AM

setTimeout and an object's methods
 
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() {
me = this;
setTimeout("me.test();",1000);
}
Foo.prototype.test = function() {
this.num++;
alert(this.type + "+" + this.num);
}

f1 = new Foo("a");
f2 = new Foo("b");
f3 = new Foo("c");

Another aspect I can't resolve is why the alert of this.type is "c" each
time. I guess the issues are being caused by the setTimeout. What's
happening and what's a better way to do this?

Andrew Poulos

Richard Cornford 03-05-2006 10:00 AM

Re: setTimeout and an object's methods
 
Andrew Poulos wrote:
> 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() {
> me = this;

^^
Assigning a value to an Identifier that is not declared in any
containing scope results in the creation of a new property of the global
object, the practical equivalent to the runtime creation of a global
variable. And there is only one property of the global object created
the first time - me = this; - is executed, subsequent executions of the
statement do not create the value they just assign that one property of
the global object a new value.

> setTimeout("me.test();",1000);

^^^^^^^^^^
The string arguments to - setTimeout - are evaluated after the timeout
has expired. The - me - identifier will be resolved at that time, to
whichever was the last value assigned to the - me - property of the
global object.

Having - setTimeout - delay for one second will give all three object
creation statements time to complete and the - me - property of the
global object will have the value of the - this - reference in the last
object created. When the three setTimouts happen - me - is the object
with the - type - of 'c' and its test method will be called 3 times,
incrementing the - num - property of that single object only.

> }
> Foo.prototype.test = function() {
> this.num++;
> alert(this.type + "+" + this.num);
> }
>
> f1 = new Foo("a");
> f2 = new Foo("b");
> f3 = new Foo("c");


These three statements will be over in milliseconds so they have all
executed prior to the first evaluation/execution of a - setTimeout -
string argument.

>
> Another aspect I can't resolve is why the alert of this.type
> is "c" each time. I guess the issues are being caused by
> the setTimeout.


The issue is being caused by trying to use one global property to refer
to many object instances. That was never going to work.

> What's happening and what's a better way
> to do this?


The 'this' shown here is trivial and pointless, so the best way of doing
it is to delete the code and forget about it. The 'this' that is your
real problem context is probably a candidate for three or four possible
approaches the base of which can only be determined by knowing what the
real 'this' actually is.

Richard.



Andrew Poulos 03-05-2006 08:30 PM

Re: setTimeout and an object's methods
 

>> Foo = function(type) {
>> this.num = 0;
>> this.type = type
>> this.trigger();
>> }
>> Foo.prototype.trigger = function() {
>> me = this;

> ^^
> Assigning a value to an Identifier that is not declared in any
> containing scope results in the creation of a new property of the global
> object,



>> What's happening and what's a better way
>> to do this?

>
> The 'this' shown here is trivial and pointless, so the best way of doing
> it is to delete the code and forget about it. The 'this' that is your
> real problem context is probably a candidate for three or four possible
> approaches the base of which can only be determined by knowing what the
> real 'this' actually is.


Thanks for the clear explanation.

My new problem is, what the appropriate way a method be called from
within another method after a defined period of time?

Andrew Poulos

Richard Cornford 03-06-2006 01:22 AM

Re: setTimeout and an object's methods
 
Andrew Poulos wrote:
<snip>
>> The 'this' shown here is trivial and pointless, so the best
>> way of doing it is to delete the code and forget about it.
>> The 'this' that is your real problem context is probably a
>> candidate for three or four possible approaches the base of
>> which can only be determined by knowing what the real 'this'
>> actually is.

>
> Thanks for the clear explanation.
>
> My new problem is, what the appropriate way a method be called
> from within another method after a defined period of time?


There are very few situations in javascript where a single 'best' or
'appropriate' way of doing anything can be determined. What should be
done usually depends a great deal on why you want to do something, and
the context in which you want to do it. You are the only person in a
position to provide that information and if you won't you probably won't
get good advice on what to do. At best you may get the first broadly
functional approach that someone chooses to suggest, but that may do you
as much harm as good in the long run.

Richard.



RobG 03-06-2006 01:27 AM

Re: setTimeout and an object's methods
 
Andrew Poulos wrote:
>
>>> Foo = function(type) {
>>> this.num = 0;
>>> this.type = type
>>> this.trigger();
>>> }
>>> Foo.prototype.trigger = function() {
>>> me = this;

>>
>> ^^
>> Assigning a value to an Identifier that is not declared in any
>> containing scope results in the creation of a new property of the global
>> object,

>
>
>
>>> What's happening and what's a better way
>>> to do this?

>>
>>
>> The 'this' shown here is trivial and pointless, so the best way of doing
>> it is to delete the code and forget about it. The 'this' that is your
>> real problem context is probably a candidate for three or four possible
>> approaches the base of which can only be determined by knowing what the
>> real 'this' actually is.

>
>
> Thanks for the clear explanation.
>
> My new problem is, what the appropriate way a method be called from
> within another method after a defined period of time?


The 'best' approach will be determined by what you are trying to do.
Start by calling it the same way you would from a totally separate function.

Given your Foo constructor:

var Foo = function(type) {
this.num = 0;
this.type = type
}

Add a 'trigger' method to the prototype that uses setTimeout to alert
the value of 'type':

Foo.prototype.trigger = function() {
setTimeout('alert("' + this.type + '");',1000);
}


'type' is evaluated when the setTimeout object is created, not when
setTimeout runs. Another way is to use a closure:

Foo.prototype.trigger = function(type) {
type = this.type;
setTimeout(function(){ alert(type); }, 1000);
}


Test it:

var f1 = new Foo('a');
var f2 = new Foo('b');
var f3 = new Foo('c');

// Call trigger() out of order
f2.trigger(); // Shows 'b'
f1.trigger(); // Shows 'a'
f3.trigger(); // Shows 'c'

f1.type = 'zz';
f1.trigger(); // Shows 'zz'


My question here is: it seems that a new function object is created each
time the trigger() method is called, is that correct? As a result, each
instance has a local 'type' variable that is given the value of the
'type' property of the object that called it (i.e. this.type).

Otherwise all calls to trigger() would show the last value that type was
set to (i.e. zz since all the code finishes before the first alert appears).

What is also happening is that a closure is formed by the setTimeout
objects having a reference to the 'type' property of the trigger
functions that called them. That may cause memory problems in IE -
though it may require quite a few calls to be significant.


Incidentally, the use of 'type' may be confusing as many DOM objects
have a type property also. You may want to make it 'objType' or
something more meaningful.

--
Rob

Richard Cornford 03-06-2006 02:35 AM

Re: setTimeout and an object's methods
 
RobG wrote:
<snip>
> Foo.prototype.trigger = function(type) {
> type = this.type;
> setTimeout(function(){ alert(type); }, 1000);
> }


If - setTimeout - executes a second later can you be certain that the -
type - property of the object still has the same value as the - type -
local variable of the outer function, and will that matter? This is why
you see such as - var self = this; -, so that the inner function could
use - self.type - and read the actual value of the pertinent object
instance property at the time of its execution.

There is also the question of how often - trigger - will be called. If
it is once then creating a new closure within the trigger function on
each execution would not matter. If - trigger - was going to be used
repeatedly it may be better to only create one closure-forming inner
function instance, i.e.:-

function Foo(type) {
var self = this;
this.num = 0;
this.type = type;
this.trigger = function(){
alert(self.type);
};
}

>
> Test it:
>
> var f1 = new Foo('a');
> var f2 = new Foo('b');
> var f3 = new Foo('c');
>
> // Call trigger() out of order
> f2.trigger(); // Shows 'b'
> f1.trigger(); // Shows 'a'
> f3.trigger(); // Shows 'c'
>
> f1.type = 'zz';
> f1.trigger(); // Shows 'zz'
>
>
> My question here is: it seems that a new function object
> is created each time the trigger() method is called, is
> that correct?


Yes it is. ECMA 262 makes provision for function objects to be 'joined'
when it not possible to distinguish between them but that cannot be true
here as each new function object has a distinct scope chain assigned to
its internal [[Scope]] property (each contains a unique
Activation/Variable object from its outer function's execution context).
There in also no evidence that any ECMAScript implementations take
advantage of the specification's provision for joining function objects.

> As a result, each instance has a local 'type' variable
> that is given the value of the 'type' property of the
> object that called it (i.e. this.type).


In effect, each instance has a unique Activation/Variable object on its
scope chain and that object has a property named 'type' that corresponds
with the outer function's local variable and holds the value of that
variable.

> Otherwise all calls to trigger() would show the last value
> that type was set to (i.e. zz since all the code finishes
> before the first alert appears).
>
> What is also happening is that a closure is formed by the
> setTimeout objects having a reference to the 'type' property
> of the trigger functions that called them.


As the - type - property is a primitive value there is no sense in which
new function can have a reference to it. The object referred to by each
function instance is the Activation/Variable object.

> That may cause memory problems in IE -
> though it may require quite a few calls to be
> significant.


No it won't. The memory leak problem is caused by circular references
(not closures as such) between javascript objects and DOM nodes
(effectively ActiveX and COM objects). There are no DOM nodes involved
here.

Richard.



Andrew Poulos 03-06-2006 10:19 AM

Re: setTimeout and an object's methods
 
Richard Cornford wrote:
> RobG wrote:
> <snip>
>> Foo.prototype.trigger = function(type) {
>> type = this.type;
>> setTimeout(function(){ alert(type); }, 1000);
>> }

>
> If - setTimeout - executes a second later can you be certain that the -
> type - property of the object still has the same value as the - type -
> local variable of the outer function, and will that matter? This is why
> you see such as - var self = this; -, so that the inner function could
> use - self.type - and read the actual value of the pertinent object
> instance property at the time of its execution.
>
> There is also the question of how often - trigger - will be called. If
> it is once then creating a new closure within the trigger function on
> each execution would not matter. If - trigger - was going to be used
> repeatedly it may be better to only create one closure-forming inner
> function instance, i.e.:-
>
> function Foo(type) {
> var self = this;
> this.num = 0;
> this.type = type;
> this.trigger = function(){
> alert(self.type);
> };
> }
>
>> Test it:
>>
>> var f1 = new Foo('a');
>> var f2 = new Foo('b');
>> var f3 = new Foo('c');
>>
>> // Call trigger() out of order
>> f2.trigger(); // Shows 'b'
>> f1.trigger(); // Shows 'a'
>> f3.trigger(); // Shows 'c'
>>
>> f1.type = 'zz';
>> f1.trigger(); // Shows 'zz'
>>
>>
>> My question here is: it seems that a new function object
>> is created each time the trigger() method is called, is
>> that correct?

>
> Yes it is. ECMA 262 makes provision for function objects to be 'joined'
> when it not possible to distinguish between them but that cannot be true
> here as each new function object has a distinct scope chain assigned to
> its internal [[Scope]] property (each contains a unique
> Activation/Variable object from its outer function's execution context).
> There in also no evidence that any ECMAScript implementations take
> advantage of the specification's provision for joining function objects.
>
>> As a result, each instance has a local 'type' variable
>> that is given the value of the 'type' property of the
>> object that called it (i.e. this.type).

>
> In effect, each instance has a unique Activation/Variable object on its
> scope chain and that object has a property named 'type' that corresponds
> with the outer function's local variable and holds the value of that
> variable.
>
>> Otherwise all calls to trigger() would show the last value
>> that type was set to (i.e. zz since all the code finishes
>> before the first alert appears).
>>
>> What is also happening is that a closure is formed by the
>> setTimeout objects having a reference to the 'type' property
>> of the trigger functions that called them.

>
> As the - type - property is a primitive value there is no sense in which
> new function can have a reference to it. The object referred to by each
> function instance is the Activation/Variable object.
>
>> That may cause memory problems in IE -
>> though it may require quite a few calls to be
>> significant.

>
> No it won't. The memory leak problem is caused by circular references
> (not closures as such) between javascript objects and DOM nodes
> (effectively ActiveX and COM objects). There are no DOM nodes involved
> here.


Thanks for all the advice (and to RobG).

I can't tell you precisely what I want to do because my client
themselves do not know precisely. Basically there are one or more images
on which "transformations" - combinations of transparency, position,
source, size... - get (non constant) periodically applied. Some of the
transformations are, for me anyway, relatively complex and so are
themselves separate methods.

On an image I need to apply a series of transformations (randomising the
delay, length of time to apply, and the actual transformation). So I saw
it as, once the initial image has loaded, as "jumping from
transformation method to transformation method.

There'll be more than one image but less than 12 images to work on.

Though, for the time being, I don't think I need any more help as I have
been given a lot to work with already by you (plural).

Andrew Poulos

VK 03-06-2006 04:30 PM

Re: setTimeout and an object's methods
 

Andrew Poulos wrote:
> 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() {
> me = this;
> setTimeout("me.test();",1000);
> }
> Foo.prototype.test = function() {
> this.num++;
> alert(this.type + "+" + this.num);
> }
>
> f1 = new Foo("a");
> f2 = new Foo("b");
> f3 = new Foo("c");
>
> Another aspect I can't resolve is why the alert of this.type is "c" each
> time. I guess the issues are being caused by the setTimeout. What's
> happening and what's a better way to do this?


I don't think you will be ever able to reach what you want in the way
you want. window.setTimeout has been implemented waaay in JavaScript
1.0 then no one even thought about constructors, prototypes and stuff.
He runs with this==window and no amount of braces around can change it.
Any attempts to stick some other "this" are going away like water off a
duck's back. So if I'm reading your intentions right:

{
{
{
... and somewhere deep in the instance curlies
setTimeout running for an instance method
...

then NOOP - you cannot do it.

There were some extensive discussion back in 90's (not here), and since
nothing dramatically changed since then, you may stick to this
solution.
You can try to transform setTimeout default into its strength. If it's
guranteed to run in the global scope, so give him a reference in a
window property - you can be sure that it will pick it up.

A sample can be found at
<http://www.geocities.com/schools_ring/archives/threads.html> and the
code posted at the end of this message - though I'm affraid newsreader
may jam everything.

This sample is a kind of overkill, because I created it while testing
script engine "thread capacity" plus some dynamic styling discrepancies
between browsers. Nevertheless the idea is clear (I hope :-)

1) You give an OID (Object ID) to each instance.
2) On thread start you add new property to the current window where the
key is instance OID and value is instance reference.
3) On thread stop you remove this property.
4) setTimeout is happy to use window[oid].method. setTimeout is happy -
you are happy :-)

P.S. If you are affraid that it's some kind of "concept profanation"
;-) then let me assure you that it's pretty close to what happens in
"big languages". There an instance also gets an OID and then roaming
with it like a transit passenger in the LA International, showing his
ID on each corner. Just in "big languages" it's all done nicely on the
lower level.

// Code from
<http://www.geocities.com/schools_ring/archives/threads.html>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html401/frameset.dtd">
<html>
<head>
<title>window.setTimeout</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">

function Timer(out) {
// Instance class name:
this.$name = 'Timer';
// Instance OID (Object ID):
this.$oid = this.$name + (new Date()).getTime();
Timer.$table[this.$oid] = this;
// Output (DOM element):
this.$out = out || null;
// Timer ID:
this.$tid = null;
// Minutes counter:
this.$min = 0;
// Seconds counter:
this.$sec = 0;
// Static methods (shared between instances):
this.start = Timer.$start;
this.$tick = Timer.$tick;
this.stop = Timer.$stop;
this.toString = Timer.toString;
}

Timer.$table = new Object();

Timer.$start = function() {
// Start timer instance:
if (this.$tid == null) {
var oid = this.$oid;
var cmd = 'self[\''+oid+'\'].$tick(\''+oid+'\')';
self[oid] = this;
this.$tid = window.setTimeout(cmd,1000);
return this.$oid;
}
}

Timer.$tick = function(oid) {
// OnTimer instance call:
with (self[oid]) {
$sec++;
if ($sec >= 60) {
$min++;
$sec = 0;
}
if ($out != null) {
$out.innerHTML = this.toString($min,$sec);
}
var cmd = 'self[\''+oid+'\'].$tick(\''+oid+'\')';
$tid = window.setTimeout(cmd,1000);
}
}

Timer.$stop = function() {
// Stop timer instance:
if (this.$tid != null) {
window.clearTimeout(this.$tid);
self[this.$oid] = null;
this.$tid = null;
}
}

Timer.toString = function(m,s) {
var t = '';
if (arguments.length < 2) {
t = 'function';
}
else {
t = (m < 10)? '0'+m : m;
t+= ':';
t+= (s < 10)? '0'+s : s;
}
return t;
}

Timer.bDown = function(e) {
// Visual change of pseudo-button on mousedown:
var evt = e || event;
if (evt) {
var trg = evt.target || evt.srcElement;
trg.style.borderStyle = 'inset';
}
}

Timer.bUp = function(e) {
// Visual change of pseudo-button on mouseup:
var evt = e || event;
if (evt) {
var trg = evt.target || evt.srcElement;
trg.style.borderStyle = 'outset';
}
}

Timer.action = function(e) {
// Display current instance data and options:
var evt = e || event;
if (evt) {
var trg = evt.target || evt.srcElement;
var oid = trg.title;
var tmp = Timer.$table[oid];
var msg = 'Instance OID: ' + oid +'\n\n';
var val = tmp.toString(tmp.$min,tmp.$sec);
if (self[oid]) {
msg+= 'Currently running\n';
msg+= 'Last value: ' + val + '\n';
msg+= 'Press Cancel to stop, press OK to keep running';
if (window.confirm(msg)) {
tmp.stop();
tmp.$out.style.color = '#CCCCCC';
}
}
else {
msg+= 'Currently idle\n';
msg+= 'Last value: ' + val + '\n';
msg+= 'Press OK to run, press Cancel to keep idle';
if (window.confirm(msg)) {
tmp.start();
tmp.$out.style.color = '';
}
}
}
}

function createTimerBox(i) {
var t = document.createElement('VAR');
t.className = 'timer';
var d = document.createElement('SPAN');
d.innerHTML = '00:00';
var b = document.createElement('B');
b.innerHTML = '?';
b.title = (new Timer(d)).start();
b.tabIndex = ++i;
b.onmousedown = Timer.bDown;
b.onmouseup = Timer.bUp;
b.onclick = Timer.action;
b.onkeypress = Timer.action;
t.appendChild(d);
t.appendChild(b);
return t;
}

function setup(i) {
if (i < 50) {
Graphics.appendChild(createTimerBox(i));
window.setTimeout('setup('+(++i)+')',100);
}
}

function init() {
// If IE then Graphics is already referenced,
// otherwise create a global reference:
if ('undefined' == typeof Graphics) {
Graphics = document.getElementById('Graphics');
}
// Fill the screen and start the mess:
window.setTimeout('setup(0)',100);
}

window.onload = init;
</script>

<style type="text/css">
body {
font: 1em Verdana, sans-serif;
color: #000000;
background-color: #F5F5F5;
margin: 20px 20px;
padding: 0px 0px}

var.timer {
display: -moz-inline-box;
display: inline-block;
position: relative;
left: 0px;
top: 0px;
margin: 5px 5px;
padding: 5px 5px;
border: medium outset;
background-color: #CCCCCC;
font-size: 0.8em;
font-style: normal;
font-weight: bold;
cursor: default}

var.timer span {
display: -moz-inline-box;
display: inline-block;
position: relative;
left: 0px;
top: opx;
margin: 5px 5px;
padding: 5px 10px;
border: medium inset;
color: #CCFF66;
background-color: #006600}

var.timer b {
display: -moz-inline-box;
display: inline-block;
position: relative;
left: 0px;
top: 0px;
margin: 5px 5px;
padding: 5px 10px;
border: medium outset;
cursor: hand;
cursor: pointer}

#Graphics {
position: relative;
left: 0px;
top: 0px
height: auto;
width: 100%;
margin: 0px 0px;
padding: 0px 0px}
</style>
</head>

<body>
<h1>Thread capacity test</h1>
<div id="Graphics"></div>
</body>
</html>


VK 03-06-2006 04:57 PM

Re: setTimeout and an object's methods
 
Heh... I decided to check if the stuff is still alive and found a bug:

....
msg+= 'Press Cancel to stop, press OK to keep running';
if (window.confirm(msg)) {
....

replace to:

....
msg+= 'Press Cancel to stop, press OK to keep running';
if (!window.confirm(msg)) {
....

Otherwise the action doesn't correspond to the chosen option. It's
strange it did not bother me year ago (? :-)


Thomas 'PointedEars' Lahn 03-06-2006 05:21 PM

Re: setTimeout and an object's methods
 
VK wrote:

> Andrew Poulos wrote:
>> 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() {
>> me = this;
>> setTimeout("me.test();",1000);
>> }
>> Foo.prototype.test = function() {
>> this.num++;
>> alert(this.type + "+" + this.num);
>> }
>>
>> f1 = new Foo("a");
>> f2 = new Foo("b");
>> f3 = new Foo("c");
>>
>> Another aspect I can't resolve is why the alert of this.type is "c" each
>> time. I guess the issues are being caused by the setTimeout. What's
>> happening and what's a better way to do this?

>
> I don't think you will be ever able to reach what you want in the way
> you want. window.setTimeout has been implemented waaay in JavaScript
> 1.0 then no one even thought about constructors, prototypes and stuff.
> [code]


Utter nonsense, as usual.


PointedEars


All times are GMT. The time now is 11:13 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.