473,563 Members | 2,668 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using timers within OO Javascript

Hey all, I'm having some trouble with window.setInter val() within a
custom object/prototype. Here is my code:

Expand|Select|Wrap|Line Numbers
  1. function MyClass() {
  2. // do some junk
  3. // ...
  4. // define methods
  5. this.m_one = function() {
  6. // nothing happens with this line. No alert, no errors
  7. window.setInterval( "this.m_two", 500 );
  8. // "error: this.m_two() is not a function"
  9. window.setInterval( "this.m_two()", 500 );
  10. // "error: m_two() is not defined"
  11. window.setInterval( "m_two()", 500 );
  12. // "error: m_two is not defined"
  13. window.setInterval( "m_two", 500 );
  14. // the following one works just fine .
  15. window.setInterval( "timer()", 500 );
  16. }
  17. this.m_two = function() {
  18. alert("m_two");
  19. }
  20. }
  21. function timer() {
  22. alert("timer");
  23. }
  24. var o = new MyClass();
  25. if( confirm( "start?" ) ){
  26. o.m_one();
  27. }
  28.  
I'm stumped on this one; how do I set another method in the object as
the callback?
Aug 4 '07 #1
10 1895
Evan Charlton wrote:
Hey all, I'm having some trouble with window.setInter val() within a
custom object/prototype. Here is my code:

[code]
function MyClass() {
Why are people so obsessed with classes when it comes to OOP? From the
above I thought you had understood that ECMAScript 3 implementations use
only prototype-based inheritance.
// do some junk
// ...
// define methods
this.m_one = function() {
// nothing happens with this line. No alert, no errors
window.setInter val( "this.m_two ", 500 );
Why should there? It is merely a not evaluated read access to the
non-existing property `m_two' *of the Global Object*.
// "error: this.m_two() is not a function"
window.setInter val( "this.m_two ()", 500 );
This is trying to call a method of the Global Object. Since the
identifier cannot be resolved, you get the runtime error.
// "error: m_two() is not defined"
window.setInter val( "m_two()", 500 );
This is trying to call an identifier without an explicit object
reference. Since the identifier cannot be resolved through the scope
chain, you get the runtime error.
// "error: m_two is not defined"
window.setInter val( "m_two", 500 );
This is trying to access an identifier without an explicit object
reference. Since the identifier cannot be resolved through the scope
chain, you get the runtime error.

As you can see, you cannot use a locally defined name in a string for
the window.setInter val() method (it would be the same with
window.setTimeo ut()). However, you can pass a Function object
reference, that is a reference to your method:

window.setInter val(this.m_two, 500);
// the following one works just fine .
window.setInter val( "timer()", 500 );
Because timer() is a globally declared function, and (so) a method of
the Global Object. "this.timer ()" should work as well.

}
this.m_two = function() {
alert("m_two");
}
}
[...]

HTH

PointedEars
--
var bugRiddenCrashP ronePieceOfJunk = (
navigator.userA gent.indexOf('M SIE 5') != -1
&& navigator.userA gent.indexOf('M ac') != -1
) // Plone, register_functi on.js:16
Aug 4 '07 #2
Thomas 'PointedEars' Lahn wrote:
As you can see, you cannot use a locally defined name in a string for
the window.setInter val() method (it would be the same with
window.setTimeo ut()). However, you can pass a Function object
reference, that is a reference to your method:

window.setInter val(this.m_two, 500);
Correction, use this instead to retain the method-object relationship:

window.setInter val(function callTwo() { this.m_two(); }, 500);
PointedEars
--
var bugRiddenCrashP ronePieceOfJunk = (
navigator.userA gent.indexOf('M SIE 5') != -1
&& navigator.userA gent.indexOf('M ac') != -1
) // Plone, register_functi on.js:16
Aug 4 '07 #3
Thomas 'PointedEars' Lahn wrote:
Thomas 'PointedEars' Lahn wrote:
>As you can see, you cannot use a locally defined name in a
string for the window.setInter val() method (it would be
the same with window.setTimeo ut()). However, you can
pass a Function object reference, that is a reference to
your method:

window.setInter val(this.m_two, 500);

Correction, use this instead to retain the method-object relationship:

window.setInter val(function callTwo() { this.m_two(); }, 500);
That is not going to help because when setInterval executes the function
expression (or the object resulting from the evaluation of the function
expression, to be precise) the - this - reference inside that function
will be to the global object and so - this.m_two - will have the same
meaning as when it was in the string in the earlier examples.

Richard.

Aug 4 '07 #4
This function may help you. It is from the Prototype javascript
library. (http://prototypejs.org/api)

Function.protot ype.bind = function() {
var __method = this, args = arguments ? arguments : [], object =
args.shift();
return function() {
return __method.apply( object, args.concat(arg uments ? arguments :
[]));
}
}

After placing this before the code below you can do this and it should
work:

instead of : window.setInter val( "this.m_two ", 500 );
use: window.setInter val( this.m_two.bind ( this ), 500 );

What bind does is copies all of the methods and properties of 'this'
object into the m_two function as a new object. I've modified it a
bit, so if this doesn't work, just add the complete prototype library
from the site listed above.

Aug 4 '07 #5
After placing this before the code below you can do this and it should
work:

instead of : window.setInter val( "this.m_two ", 500 );
use: window.setInter val( this.m_two.bind ( this ), 500 );

What bind does is copies all of the methods and properties of 'this'
object into the m_two function as a new object. I've modified it a
bit, so if this doesn't work, just add the complete prototype library
from the site listed above.
Alternatively, if you don't need to access any of the class's
properties in "m_two", just do what Thomas said above:
As you can see, you cannot use a locally defined name in a string for
the window.setInter val() method (it would be the same with
window.setTimeo ut()). However, you can pass a Function object
reference, that is a reference to your method:

window.setInter val(this.m_two, 500);
Aug 4 '07 #6
Richard Cornford wrote:
Thomas 'PointedEars' Lahn wrote:
>Thomas 'PointedEars' Lahn wrote:
>> window.setInter val(this.m_two, 500);
Correction, use this instead to retain the method-object relationship:

window.setInter val(function callTwo() { this.m_two(); }, 500);

That is not going to help because when setInterval executes the function
expression (or the object resulting from the evaluation of the function
expression, to be precise) the - this - reference inside that function
will be to the global object and so - this.m_two - will have the same
meaning as when it was in the string in the earlier examples.
True, a closure is required:

this.m_one = function()
{
var me = this;
window.setInter val(function() { me.m_two(); }, 500);
};

this.m_two = function()
{
window.alert(th is.m_one);
};
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not the
best source of advice on designing systems that use javascript.
-- Richard Cornford, <f8************ *******@news.de mon.co.uk>
Aug 4 '07 #7
Thomas 'PointedEars' Lahn schrieb:
Thomas 'PointedEars' Lahn wrote:
>As you can see, you cannot use a locally defined name in a string for
the window.setInter val() method (it would be the same with
window.setTime out()). However, you can pass a Function object
reference, that is a reference to your method:

window.setInter val(this.m_two, 500);

Correction, use this instead to retain the method-object relationship:

window.setInter val(function callTwo() { this.m_two(); }, 500);
You're wrong!

You definitely need closures for this, if you need access to this object:

function MyClass() {
//..
this.m_one = function() {
var me = this; // create a closure
this.interval = window.setInter val( function(){
me.m_two();
}, 1000 );
}
//..
}

br | rb
--
Sie freuten sich riesig, wenn eine Maschine nach sechs Stunden etwas
fertig brachte, wozu jeder Mensch auf der Straße für 2 Cent fähig
gewesen wäre. Anschließend ließen sie sich Bananen- und Sushi-Pizza
kommen und schliefen vor der Tastatur ein. [aus T.P., Heiße Hüpfer]
Aug 4 '07 #8
ja******@gmail. com wrote:
Alternatively, if you don't need to access any of the class's
properties in "m_two", just do what Thomas said above:
[...]
*sigh* *There* *is* *no* *class*. My sig happens to be proved by your
statement.
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not the
best source of advice on designing systems that use javascript.
-- Richard Cornford, <f8************ *******@news.de mon.co.uk>
Aug 4 '07 #9
ja******@gmail. com wrote:
This function may help you. It is from the Prototype
javascript library. (http://prototypejs.org/api)

Function.protot ype.bind = function() {
var __method = this, args = arguments ? arguments : [], object =
args.shift();
return function() {
return __method.apply( object, args.concat(arg uments ? arguments :
[]));
}
}
You have got to be joking. That is far too bad even for Prototype.js
code. I know that they have long since broken compatibility with ECMA
262 3rd Ed. but that is not even going to work in common browser
environments.

And what do they think - args = arguments ? arguments : [] - is about?
The existence of an - arguments - object, and that the Identifier
'arguments' will refer to that object, is absolutely guaranteed (short
of jumping through some extreme hoops with things like -
with({arguments :null}){ args = arguments?argum ents:[];} -). And even
if - arguemtns - were allowed not exist the code would likely error out
at the first reference to it whenever it didn't. It would be difficult
to make this stuff up if you tried.
After placing this before the code below you can do this and
it should work:

instead of : window.setInter val( "this.m_two ", 500 );
use: window.setInter val( this.m_two.bind ( this ), 500 );

What bind does is copies all of the methods and properties of
'this' object into the m_two function as a new object.
No it does not, and if it did that would be a disaster in this context
(and very many others) as the copy would be a copy of the state of the
object at the time of the setInterval call and so the method would end
up acting on an object with a (potentially) out-of-date state, and if it
needed to change the state of its object it would not be able to, but
instead would only change the state of the copy.
I've modified it a bit,
So what precisely did you modify? That is, how broken was it before you
started playing with it?
so if this doesn't work,
If? When it doesn't work! Opera may be the only browser where this does
work, and that is because of an ECMAScript bug in Opera.
just add the complete prototype library
from the site listed above.
Considering how utterly trivial the solution(s) to this problem is(are)
if you understand what you are doing, that has got to be one of the
worst suggestions possible.

Richard.

Aug 4 '07 #10

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

Similar topics

14
9562
by: Michael Winter | last post by:
In an attempt to answer another question in this group, I've had to resort to calling the DOM method, Node.removeChild(), using a reference to it (long story...). That is, passing Node.removeChild. In Opera (7.23/Win), the call appears to do nothing - the node remains - but no errors are shown. In Netscape (7.0/Win), an exception results....
1
6017
by: Antoine | last post by:
Hello, Does anybody know a way to retreive the running timers (their ids) in a html page? I cannot find something in the html dom at first sight. Is there collection of timers available (like window.all, forms, frames and such)? Some other way? When you create a timer (setTimeout), the return value is the timer id.
18
3240
by: Max | last post by:
This is a follow-up on my previous thread concerning having the program wait for a certain date and time and then executing some code when it gets there. My question is; can I use the Sleep function from kernel32 to accomplish this? My concern is that this function takes milliseconds where my program needs to be accurate to within 5 minuets,...
6
17149
by: ransoma22 | last post by:
I developing an application that receive SMS from a connected GSM handphone, e.g Siemens M55, Nokia 6230,etc through the data cable. The application(VB.NET) will receive the SMS automatically, process and output to the screen in my application when a message arrived. But the problem is how do I read the SMS message immediately when it arrived...
7
5662
by: FredC | last post by:
I need some insight into timers, the static modifier and instance memory safety. public class myClass { protected static int i = 0; portected float myfloat; protected static Timer staticTimer = new Timer(); } public class myObject: myClass
9
2868
Shashi Sadasivan
by: Shashi Sadasivan | last post by:
In my current application, I have to set cettain defaults to controls that are displayed or are used. so i have a class to which i send the form as a control, and iterate through each of its controls and child controls However, I have to also edit the Interval property of any timers present in the form. Timers come under the...
8
3358
by: Ollie Riches | last post by:
I'm looking into a production issue related to a windows service and System.Timers.Timer. The background is the windows service uses a System.Timers.Timer to periodically poll a directory location on a network for files and then copies these files to another location (on the network) AND then updates a record in the database. The file copying...
1
2088
by: shawnwperkins | last post by:
Hi Guys, I'm new to Javascript and have a couple of questions that I hope someone could quickly answer for me. First, I'm trying to modify an example Ajax script to fit my needs. The script is located here: http://ajaxify.com/run/time/periodicRefresh/
0
958
by: =?Utf-8?B?VEQgaXMgUFNQ?= | last post by:
I've created a page where the user can browse for a file on his local computer and then click an upload button. I'm not using FileUpload. When the user clicks on the upload button my program uses FTP to upload the file to the server within the server's ftp site. Since these files are typically quite large I would like to provide my users...
0
7664
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...
0
8106
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...
1
7638
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...
0
7948
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5484
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...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3642
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...
1
1198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
923
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.