473,698 Members | 2,662 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
10 1920
Thomas 'PointedEars' Lahn wrote:
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
relationshi p:

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:
A closure is (or probably is) required, but only one.
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);
};
As you have it every call to - m_one - will create a new function object
and a new closure. But if the closure was formed in the constructor (or
by other means (e.g. in an external function), but once only) with the -
m_two - method then the result would be more efficient.

function AnObject(){
var self = this;
this.m_two = function(){
// have this function refer to its object instance through the
// scope chain instead of through the - this - keyword and
// you only need one instance of this function
alert(self.m_on e);
};
}

// and - m_one - does not need to created in the constructor
AnObject.protot oype.m_one = function(){
setInterval(thi s.m_two, 500);
};

And if the idea of creating the closure at the time of instantiation the
object did not appeal the 'Russian Doll' pattern (or similar) could be
applied to create it once, but at the first call to - m_one -.

function AnObject(){
}

AnObject.protot oype.m_two = function(){
alert(this.m_on e);
};

AnObject.protot oype.m_one = function(){
var self = this;
function atIntervals(){
self.m_two();
}
(this.m_one = function(){
// This is the function that calls to - obj.m() - once use
directly
// following its indirect use in the first call.
setInterval(atI ntervals, 500);
})();
};
Prototype.js was written by ...
One of my gripes about Prototype.js is the way in which it encourages
(even forces) horrendously inefficient use of functions, and especially
functions that are 'bound' to objects. You will often see Prototype.js
code where in real javascript you cold define/use a single instance of a
function and re-use it to your hart's content being implemented so that
a new function object is created on each and every use, or worse, a new
function created and then another with its own closure as the first is
'bound' to some object, but the same object on each occasion.

Richard.

Aug 4 '07 #11

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

Similar topics

14
9583
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. On IE (6.0/Win), the node is removed. Strangly, if I pass another function reference, say...
1
6026
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
3256
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, and delays may be as long as a number of days, months or whatever. Would I run into many problems...
6
17195
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 without my handphone BeEPINg for new message ? I read up the AT commands, but when getting down...
7
5674
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
2897
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 Windows.Forms.Timer namespace and i am currently iterating through all the Controls in the form. How would I...
8
3368
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 is performed before the database update because the file system is not transactional. The code...
1
2100
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
965
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 with some feedback that shows things like the the number of total bytes and the number of bytes...
0
8674
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
9157
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
9023
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...
0
7721
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6518
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
5860
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3045
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
2
2327
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1999
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.