美文网首页
CocosCreator中,setTimeout的使用

CocosCreator中,setTimeout的使用

作者: 全新的饭 | 来源:发表于2022-10-18 10:34 被阅读0次

参考

JavaScript setTimeout() 用法详解

示例

运行后,在3秒后调用方法myFunc。在myFunc中,调用了方法getCurTime。


image.png
import { _decorator, Component, Node, Vec3, absMax, Label } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Test')
export class Test extends Component
{
    start():void
    { 
        console.info("~~~~~00:" + this.getCurTime());
        // 3秒后执行
        setTimeout(()=>this.myFunc(), 3000);
    }

    myFunc(): void
    { 
        console.info("~~~~~11:" + this.getCurTime());
    }

    getCurTime(): string
    { 
        const date = new Date();
        const str = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
        return str;
    }
}

使用说明

  1. 参数单位是毫秒,不是秒。
  2. 它的this是window,所以传递要执行的方法时,不能写成
    setTimeout(this.myFunc, 3000);
报错信息

因为myFunc中调用了自己this中的方法getCurTime,当window作为this时,window中并没有getCurTime这个方法。
要写成

    setTimeout(()=>this.myFunc(), 3000);

对于箭头函数中的 this,其指向直接包含此箭头函数定义的函数所属的对象。

相关文章

网友评论

      本文标题:CocosCreator中,setTimeout的使用

      本文链接:https://www.haomeiwen.com/subject/iemjzrtx.html