在JavaScript中使用timer示例
更新時間:2014年05月08日 09:18:27 作者:
這篇文章主要介紹了在JavaScript中如何使用timer,并給出各種測試case的例子,需要的朋友可以參考下
復(fù)制代碼 代碼如下:
function foo()
{
}
setInterval( "foo()", 1000 );
如果使用OO的技術(shù),可以這樣,
復(fù)制代碼 代碼如下:
// 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 的方法可以這樣。
復(fù)制代碼 代碼如下:
function Another()
{
var obj = nw MyObj();
setInterval( “obj.timer()”, 1000 );
}
顯然,它可以正確工作,但如果你是一個完美主義者,你就不會對它滿意。幸運(yùn)的是,可以將這個動作放到構(gòu)造函數(shù)中去,形式上有點變化。
復(fù)制代碼 代碼如下:
// 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的例子。
復(fù)制代碼 代碼如下:
<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>
相關(guān)文章
electron-builder允許安裝時請求提升權(quán)限的場景分析
electron-builder 作為一個用于 Electron 應(yīng)用程序打包的工具,需要下載并使用 Electron 運(yùn)行時來創(chuàng)建可執(zhí)行文件,這篇文章給大家介紹electron-builder允許安裝時請求提升權(quán)限的相關(guān)知識,感興趣的朋友跟隨小編一起看看吧2024-03-03
javascript函數(shù)自動執(zhí)行常用方法匯總
本文給大家匯總介紹了3種javascript函數(shù)自動執(zhí)行的常用方法,非常的簡單實用,有需要的小伙伴可以參考下2016-03-03
javascript在事件監(jiān)聽方面的兼容性小結(jié)
javascript 在事件監(jiān)聽方面的兼容性總結(jié),注意是由于多個瀏覽器的不一致,導(dǎo)致大家在js書寫時需要考慮多個瀏覽器的兼容性。2010-04-04
ElementPlus?Tag標(biāo)簽用法小結(jié)
這篇文章主要介紹了ElementPlus?Tag標(biāo)簽用法,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09
javascript中window.location.href的用法
window.location.href?是一個用于獲取當(dāng)前頁面?URL?或讓瀏覽器跳轉(zhuǎn)到新?URL?的重要方法,本文就詳細(xì)的介紹一下javascript中window.location.href的用法,感興趣的可以了解一下2023-08-08
在Postman的腳本中如何使用pm對象獲取接口的請求參數(shù)
這篇文章主要介紹了在Postman的腳本中如何使用pm對象獲取接口的請求參數(shù),本文通過實例代碼圖文相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09

