网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的范文:

 

标题 在JavaScript中使用timer示例
范文
    这篇文章主要介绍了在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()这个函数并不能识别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 © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/24 0:09:21