This article mainly introduces how to use timer in JavaScript and provides examples of various test cases. For more information, see
The Code is as follows:
Function foo ()
{
}
SetInterval ("foo ()", 1000 );
If OO technology is used,
The Code is as follows:
// 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.
The Code is 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.
The Code is as follows:
// 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.
The Code is as follows:
<BR> Hello Timer <BR>