在JavaScript中使用timer示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

在JavaScript中使用timer示例

  2020-05-13 我要评论
复制代码 代码如下:

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()这个函数并不能识别this这个变量。一个workaround 的方法可以这样。
复制代码 代码如下:

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

显然,它可以正确工作,但如果你是一个完美主义者,你就不会对它满意。幸运的是,可以将这个动作放到构造函数中去,形式上有点变化。
复制代码 代码如下:

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们