473,698 Members | 2,082 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help using setInterval within an object function

Hi-

I am trying to use setInterval to call a method within an object and
have not had any luck. I get "Object doesn't support this property or
method" when I execute the following code. What I am doing wrong?

Your help will be much appreciated.
Thanks
<script language="Javas cript">

function someObject(){
}

someObject.prot otype.showNext = function(){
alert('listenin g...');
}

//i've tried this:
someObject.prot otype.startList ening = function(){
this.interval = setInterval('th is.showNext()', 2000);
}

//and this:
someObject.prot otype.startList ening = function(){
this.interval = setInterval(thi s.showNext(), 2000);

/*

is 'this.showNext( )' referencing setInterval and not my object?

*/
}
var x = new someObject();
x.startListenin g();

</script>

Jul 23 '05 #1
6 15219
I am not sure that this helps, but:-

OPTION 1
this.interva l = setInterval(thi s.showNext(), 2000);


Remove the ( ) as these call the function. You want to pass a reference
to the function instead, thus:

this.interval = setInterval(thi s.showNext, 2000);

OPTION 2

Use a closure:-

someObject.prot otype.startList *ening = function()
{
this.interval = setInterval(sho wNext, 2000);

function showNext()
{
alert('listenin g...');
}
}

Julian

Jul 23 '05 #2
marktm wrote:
I am trying to use setInterval to call a method within an
object and have not had any luck. I get "Object doesn't
support this property or method" when I execute the
following code. What I am doing wrong? <snip> <script language="Javas cript">
The language attribute of script elements is deprecated in HTML 4, and
the type attribute is required (rendering the language attribute
redundant). Only attempting to script formally valid HTML removes an
entire category of potential cross-browser scripting pitfalls (saves a
lot of effort and trouble in the long run), but the script elements
themselves need to be valid in order not to have the validator flag them
as erroneous:-

<script type="text/javascript">
function someObject(){
}

someObject.prot otype.showNext = function(){
alert('listenin g...');
}

//i've tried this:
someObject.prot otype.startList ening = function(){
this.interval = setInterval('th is.showNext()', 2000);
Strings used as the first argument to setTimout/Interval are evaluated
and executed in the global scope, and in the global scope the - this -
keyword is a reference to the global object. The global object does not
have a - showNext - method (unless you give it one) so that code will
error, as described.
}

//and this:
someObject.prot otype.startList ening = function(){
this.interval = setInterval(thi s.showNext(), 2000);
But the behaviour was different here as this code put up the alert box,
it did so when the setInterval function was fist called (and only once).

This expression has called the - showNext - method of the object
instance and it is the return value form that function call that is
passed to the setInterval function as an argument. The - showNext -
method returns - undefined - so the first argument to the setInterval
function will likely be type converted into the string "undefined" ,
which is a pointless expression when executed in the global context on
more modern browsers, and an error (E.G.: IE 4 -> "undefined is
undefined") on older ones.
/*

is 'this.showNext( )' referencing setInterval and not my object?
setInterval/Timeout has no knowledge of the context in which it is used.
It's arguments are either a string that will be evaluated/executed in
the global context, or a function reference where the function will be
executed as a function (not as a method of an object, i.e. the - this -
keyword will always refer to the global object).
}

var x = new someObject();
x.startListenin g();

</script>


If the desire is to retain the association of the function call with an
object instance (which is not worthwhile unless the method called
actually refers to an object instance (uses the - this - keyword)), then
with string arguments a globally accessible reference to the object
instance would need to be created (or an existing one used). In this
case you have a global variable - x - referring to the object instance
so:-

setInterval( "x.showNext();" , 1000);

- would work, but be a terrible design as it would have made a detail of
how the object was to be used internal to the object, and you would only
be able to ever use one instance of the object (suggesting an entirely
difference approach from the outset).

To be useful the string argument would need to know how to refer to
distinct object instances without any interest in how those objects were
being employed by external code (anonymously).

This can be done, for example, by having each object constructed create
an unique global reference to itself. E.G:-

function someObject(){
this.index = someObject.inst ances.length;
someObject.inst ances[this.index] = this;
}

someObject.inst ances = [];

someObject.prot otype.startList ening = function(){
this.interval = setInterval(
'someObject.ins tances['+this.index+'].showNext()',
2000
);
}

- Which is a bit cumbersome, and leaves you with an array of all objects
created (so they will not be garbage collected if otherwise freed,
unless an explicit 'destroy' facility is provided and used to remove the
references from the globally accessible array).

Using function references as the first argument to setTimeout/Interval,
while preserving the association with an object instance, is simpler to
arrange and more complex to understand as it requires closures. See:-

<URL: http://jibbering.com/faq/faq_notes/closures.html >

And some older browsers do not understand function references as the
first argument to the setTimeout/Interval functions, only strings
(though that can be worked around).

Richard.
Jul 23 '05 #3
OPTION 3

Sorry, taking account of what Richard has said, a more accurate example
of a closure would be:-

someObject.prot otype.showNext = function()
{
alert('listenin g...');
};

someObject.prot otype.startList **ening = function()
{
var oInstance=this; // CAPTURE THIS

this.interval = setInterval(fun ction(){oInstan ce.showNext()},
2000);
// oINSTANCE IS "CLOSED" INSIDE THE ANONYMOUS FUNCTION
};

Jul 23 '05 #4
Thanks!

Jul 23 '05 #5
Use the 2nd way, but leave off the parentheses:
this.interval = setInterval(thi s.showNext, 2000);
Reason:
Method 1 fails because it is interpretted as a function called "this" -- it
is in quotes.
Method 2 fails because with the parentheses and not in quotes, the function
is executed immediately, and in fact could return another function as the
value to be "called".
Clear, sort of?
....Jim Lee, Dallas, TX...

"marktm" <ma****@gmail.c om> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
Hi-

I am trying to use setInterval to call a method within an object and
have not had any luck. I get "Object doesn't support this property or
method" when I execute the following code. What I am doing wrong?

Your help will be much appreciated.
Thanks
<script language="Javas cript">

function someObject(){
}

someObject.prot otype.showNext = function(){
alert('listenin g...');
}

//i've tried this:
someObject.prot otype.startList ening = function(){
this.interval = setInterval('th is.showNext()', 2000);
}

//and this:
someObject.prot otype.startList ening = function(){
this.interval = setInterval(thi s.showNext(), 2000);

/*

is 'this.showNext( )' referencing setInterval and not my object?

*/
}
var x = new someObject();
x.startListenin g();

</script>

Jul 23 '05 #6
Jimnbigd wrote:
Use the 2nd way, but leave off the parentheses:
this.interval = setInterval(thi s.showNext, 2000);
Which will loose the association with the object instance and so be
useless in real world examples.
Reason:
Method 1 fails because it is interpretted as a function
called "this" -- it is in quotes. <snip>

Nothing is interpreted 'as a function called "this"', the - this -
keyword, in this context, is interpreted as a reference to the global
object, and - this.showNext - is interpreted as a property of the global
object. Because that property is not defined an error is generated when
it is called as a method.

If you are going to post answers to questions that have already been
answered twice it would be a good idea to read and understand the other
answers, and not be posting responses that are factually wrong and
disregard an important detail that has been covered in those other
answers.
"marktm" <ma****@gmail.c om> wrote ...

<snip>

Please do not top-post on comp.lang.javas cript, see the FAQ for details.

Richard.
Jul 23 '05 #7

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

Similar topics

28
20327
by: Daniel | last post by:
Hello =) I have an object which contains a method that should execute every x ms. I can use setInterval inside the object construct like this - self.setInterval('ObjectName.methodName()', this.pinginterval); - but is there no way to do this without using the literal ObjectName? If I write 'this.methodName()' I get "Line 1 Char 1: Object doesn't support this property or method." in IE, and nothing happens in Firebird.
10
7785
by: Richard A. DeVenezia | last post by:
At line this.timerId = setInterval (function(){this.step()}, 100) I get error dialog Error:Object doesn't support this property or method. If I change it to this.timerId = setInterval (function(){this==window}, 100) I see true, the sad fact that 'this' is window and not an anim. What are some proper ways ? I would like to avoid
5
1248
by: Jamiil | last post by:
Using Microsof Front Page, I am trying to display the time on the Status Line, however, to no avail. Here is a snip of the code code: ...\dev\JavaScript\DisplayTimeInStatusLine.js <HTML> <HEAD> <script type="text/javascript"> //This function displays the time in the status line //Invoke it once tho activate the clock; it will call itself from then on.
3
5805
by: shawn | last post by:
Hi All Was trying to get this bit of code working (simplified of course) for (i=0;i<uuid_num;i++) { window.setInterval(InitMap(uuidValues), timePeriod); } Where uuid_num, uuidValues, timePeriod are defined above, along with function InitMap.
2
3286
by: alxasa | last post by:
Hi, I have a setInterval which executes its command every 10 seconds in a infinite loop. I've got something real basic like: var processes=0; function startme(){ if(stopthisloop>1)
10
1920
by: Evan Charlton | last post by:
Hey all, I'm having some trouble with window.setInterval() within a custom object/prototype. Here is my code: function MyClass() { // do some junk // ... // define methods this.m_one = function() { // nothing happens with this line. No alert, no errors
2
2782
by: shawnwperkins | last post by:
Hi Folks, I'm new to Javascript and just need a little help. I downloaded a script from Dynamic Drive's Web site and I'm trying to make a simple modification and could use some help. :) The script below fetches data from the web server and displays it in the form as a ticker on the web page. See: http://www.dynamicdrive.com/dynamicindex2/ajaxticker.htm What I would like to do is to have the Ajax ticker periodically go out
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/
53
8389
by: souporpower | last post by:
Hello All I am trying to activate a link using Jquery. Here is my code; <html> <head> <script type="text/javascript" src="../../resources/js/ jquery-1.2.6.js"</script> <script language="javascript" type="text/javascript">
0
8671
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
8598
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
9152
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
9016
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
8887
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
6515
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
5858
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();...
0
4360
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...
2
2321
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.