在JavaScript中使用timer示例
來源:易賢網(wǎng) 閱讀:2695 次 日期:2014-05-09 15:36:22
溫馨提示:易賢網(wǎng)小編為您整理了“在JavaScript中使用timer示例”,方便廣大網(wǎng)友查閱!

這篇文章主要介紹了在JavaScript中如何使用timer,并給出各種測試case的例子,需要的朋友可以參考下

代碼如下:

function foo()

{

}

setInterval( "foo()", 1000 );

如果使用OO的技術,可以這樣,

復制代碼 代碼如下:

// 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();

}

但是,它并不能像你想像的那樣工作。原因在于setInterval()這個函數(shù)并不能識別this這個變量。一個workaround 的方法可以這樣。

代碼如下:

function Another()

{

var obj = nw MyObj();

setInterval( “obj.timer()”, 1000 );

}

顯然,它可以正確工作,但如果你是一個完美主義者,你就不會對它滿意。幸運的是,可以將這個動作放到構造函數(shù)中去,形式上有點變化。

代碼如下:

// 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, 通過使用一個閉包,就可以了。至于其中的原因,我想給讀者自己去思考。

最后,給一個各種測試case的例子。

代碼如下:

<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>

更多信息請查看IT技術專欄

更多信息請查看網(wǎng)絡編程
易賢網(wǎng)手機網(wǎng)站地址:在JavaScript中使用timer示例
關于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關注公眾號:hfpxwx
咨詢QQ:526150442(9:00—18:00)版權所有:易賢網(wǎng)