Home  >  Article  >  Web Front-end  >  Example of using timer in JavaScript_javascript tips

Example of using timer in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:49:311467browse
Copy code The code is as follows:

function foo()
{
}
setInterval( "foo()", 1000 );

If you use OO technology, you can do this,
Copy code 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 doesn't work as you think. The reason is that the setInterval() function does not recognize the variable this. A workaround approach could be like this.
Copy code The code is as follows:

function Another()
{
var obj = nw MyObj();
setInterval( "obj.timer()", 1000 );
}

Obviously, it can work correctly, but if you are a perfectionist Otherwise, you won't be satisfied with it. Fortunately, you can put this action into the constructor, with a slight change in form.
Copy code 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, by using a closure, that's it. As for the reasons, I want to leave it to the readers to think for themselves.

Finally, give an example of various test cases.
Copy code The code is as follows:



<br>Hello Timer <br>






Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn