FrameExecute.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { _decorator, Component, Node } from 'cc';
  2. import { Singleton } from './Singleton';
  3. const { ccclass, property } = _decorator;
  4. @ccclass('FrameExecute')
  5. export class FrameExecute extends Component {
  6. //单例
  7. private static _instance: FrameExecute;
  8. public static getInstance(): FrameExecute {
  9. return Singleton.getInstance(FrameExecute);
  10. }
  11. /**
  12. * 分帧执行
  13. * @param fun 执行函数
  14. * @param target 执行函数对象
  15. * @param start 起始次数 (从0开始,0表示执行第1次)
  16. * @param max 最大执行次数 (例如5则表示函数总共执行5次)
  17. * @param executeTime 分配的执行时间
  18. * @param data 传递数据
  19. * @returns
  20. */
  21. public execute(fun: Function, target: any, start: number, max: number, executeTime: number, data: any = null) {
  22. //获取开始时间
  23. let startTime = new Date().getTime();
  24. //执行计数
  25. let count = start;
  26. //开始执行函数,如果超过分配的执行时间,则延迟到下一帧执行
  27. while (count < max) {
  28. //执行函数
  29. fun.call(target, count, data);
  30. //获取消耗时间
  31. var costTime = new Date().getTime() - startTime;
  32. console.log("执行耗时:", costTime);
  33. //消耗时间 > 分配的时间,则延迟到下一帧执行
  34. if (costTime > executeTime) {
  35. console.log("超时,进入下一轮加载");
  36. this.scheduleOnce(() => { this.execute(fun, target, count + 1, max, executeTime, data) });
  37. return;
  38. }
  39. count++;
  40. }
  41. }
  42. }