Use the timer example in JavaScript

  • 2020-03-30 02:49:55
  • OfStack

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

If you use OO techniques, you can do this,
 
// 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(); 

} 

But it doesn't work the way you think. The reason is that the setInterval() function does not recognize this variable. A workaround method can look like this.
 
function Another() 
{ 
var obj = nw MyObj(); 
setInterval(  " obj.timer() " , 1000 ); 
} 

Obviously, it works correctly, but if you're a perfectionist, you won't be happy with it. Fortunately, you can put this action in the constructor, which is a little bit different.
 
// 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, just by using a closure. As to why, I want to leave the reader to think for himself.

Finally, give an example of various test cases.
 
<html> 
<head> 
<title> 
Hello Timer 
</title> 
<script language = "JScript"> 

 

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> 

Related articles: