It is easy to use timer in Javascript,
Function Foo ()
{
}
Setinterval ("Foo ()", 1000 );
If OO technology is used,
// Constructor
Function myobj
{
Function Foo ()
{
Alert (this. data );
}
This. Timer = Foo;
This. Data = "hello ";
Setinterval ("This. Timer ()", 1000 );
}
Function another ()
{
// Create timer when create object
VaR OBJ = new myobj ();
}
However, it cannot work as you think. The reason is that the setinterval () function does not recognize this variable. A workaround method can be as follows.
Function another ()
{
VaR OBJ = NW myobj ();
Setinterval ("obj. Timer ()", 1000 );
}
Obviously, it works right, but if you are a perfectionist, you will not be satisfied with it. Fortunately, this action can be put into the constructor, and the form changes a bit.
// Constructor
Function myobj
{
Function Foo ()
{
Alert (this. data );
}
This. Timer = Foo;
This. Data = "hello ";
VaR self = this;
Setinterval (function () {self. Timer () ;}, 1000 );
}
Function another ()
{
VaR OBJ = new myobj ();
}
OK. You can use a closure. As for the reason, I want to give it to readers.
Finally, let's give an example of various test cases.
<HTML>
<Head>
<Title>
Hello Timer
</Title>
<Script language = "jscript">
/*
* There are 3 classes.
*
* 1. timer can run and result is OK
* 2. timer can run and result is wrong
* 3. timer can not run
*
*/
Function OBJ ()
{
Function Foo ()
{
Alert (this. Timer );
}
This. Timer = Foo;
//
VaR me = this;
VaR F = function () {me. Timer ();};
VaR F2 = function () {This. Timer ();};
// 1st Class
// Setinterval (F, 1000 );
// 3rd class
// Setinterval (F2, 1000 );
// 2nd Class
// Setinterval (Me. Timer, 1000 );
// Setinterval (this. Timer, 1000 );
// Setinterval (Foo, 1000 );
// 3rd class
// Setinterval ("This. Timer ()", 1000 );
// Setinterval ("me. Timer ()", 1000 );
// Setinterval ("Foo ()", 1000 );
}
VaR o = NULL;
Function onclick ()
{
O = new OBJ ();
// 1st Class
// Setinterval ("O. Timer ()", 1000 );
Setinterval (function () {o. Timer () ;}, 1000 );
// 2nd Class
// Setinterval (O. Timer, 1000 );
}
</SCRIPT>
</Head>
<Body>
<Input type = "button" onclick = "onclick ()" value = "Click me"> </input>
</Body>
</Html>