Tips for using timer example _ JavaScript in javascript

Source: Internet
Author: User
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>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.