2.4JS中的函数的使用

什么是JS的函数:

类似于java中的方法,JS中也可以定义一些函数,java中的方法签名包含访问修饰符,返回值类型,方法名,参数列表,异常列表,但是JS中定义函数的语法相对简单很多,主要以function作为函数关键字,具备函数名和参数列表,但是没有访问修饰符也没有返回值类型关键字和异常列表

函数定义的三种语法

<!DOCTYPE html>
<html>
        <head>
                <meta charset="UTF-8">
                <title></title>
                <script>
                        /*
                         * 第一种语法格式 常见
                         * function 函数名(参数列表){js代码}
                         * 
                         * 
                         * 第二种语法
                         * var 函数名=function(参数列表){JS代码}
                         * 
                         * 第三种语法 不常用 了解
                         * var 函数名=new Function('js代码')
                         * 
                         * */
                        function fun1(){
                                alert("你好");
                        }
                        
                        var fun2=function(){
                                alert("你很好")
                        }
                        
                        var fun3=new Function('alert("你非常好");');
                        
                        // 调用方法
                        fun1();
                        fun2();
                        fun3();
                </script>
        </head>
        <body>
        </body>
</html>

函数参数和返回值

<!DOCTYPE html>
<html>
        <head>
                <meta charset="UTF-8">
                <title></title>
                <script>
                        /*
                         *
                         * 1传入的实参可以和形参个数不一致 
                         * 2如果函数中有返回值,那么直接用return关键字返回即可
                         * */
                        function fun1(a,b,c){
                                alert("a:"+a);
                                alert("b:"+b);
                                alert("c:"+c);
                        }
                        
                        //fun1(10,"hello js",false);
                        // 少传参数 OK
                        //fun1(1,2);
                        // 多传参数 OK 多出来的参数相当于没传
                        //fun1(10,"hello js",false,new Date());
                        
                        
                        function fun2(a,b){
                                var c=a*b;
                                return c;
                        }
                        
                        //var x =fun2(10,20);
                        //alert(x)
                        
                        // 方法本身作为参数(了解)
                        
                        function funa( i ,j){
                                return i+j;
                        }
                        
                        function funb(a){
                                return a(10,20);
                        }
                
                        var sum =funb(funa)
                        alert(sum)
                        
                        
                </script>
        </head>
        <body>
        </body>
</html>

<think>我们正在讨论的是Cocos Creator 2.4中的`scheduleOnce`方法。用户之前的问题是关于缓动(tween)的暂停和恢复,现在转向了`scheduleOnce`的恢复。需要注意的是,`scheduleOnce`和`tween`是两种不同的定时机制。 在Cocos Creator中,`scheduleOnce`是一个用于安排一个只执行一次的函数的方法,它属于组件的定时器系统。与`tween`不同,`scheduleOnce`本身并没有提供直接的暂停和恢复方法。但是,我们可以通过一些技巧来实现类似的功能。 ### 关键点 1. **`scheduleOnce`的本质**:它会在指定的延迟时间后执行一次回调函数,然后自动取消。 2. **暂停**:Cocos Creator的组件定时器系统提供了`unschedule`来取消一个已安排的函数,但是取消后无法直接恢复,因为`scheduleOnce`是一次性的。 3. **恢复**:如果我们想要在暂停后继续执行,我们需要记录已经过去的时间,然后在恢复时重新安排剩余时间的延迟。 ### 解决方案 我们可以通过以下步骤实现: - 当需要暂停时,取消当前的`scheduleOnce`,并记录已经过去的时间(通过记录开始时间和当前时间差)。 - 恢复时,使用剩余时间(总延迟时间 - 已过去的时间)重新调用`scheduleOnce`。 ### 具体代码实现 ```typescript export default class MyComponent extends cc.Component { private callback: Function = null; // 要执行的回调函数 private totalDelay: number = 0; // 总延迟时间 private startTime: number = 0; // 开始计时的时间 private remainingTime: number = 0; // 剩余时间 private isScheduled: boolean = false; // 是否已经安排 private isPaused: boolean = false; // 是否暂停 // 安排一次延迟执行 scheduleMyOnce(delay: number, callback: Function) { this.totalDelay = delay; this.callback = callback; this.startTime = Date.now(); this.isScheduled = true; this.isPaused = false; // 使用scheduleOnce this.scheduleOnce(() => { if (this.isPaused) return; // 如果处于暂停状态,则不执行 callback(); this.isScheduled = false; }, delay); } // 暂停 pauseSchedule() { if (!this.isScheduled || this.isPaused) return; // 取消当前安排 this.unschedule(this.callback); // 计算已经过去的时间 const elapsed = Date.now() - this.startTime; this.remainingTime = this.totalDelay - elapsed / 1000; // 因为scheduleOnce使用秒,Date.now是毫秒 this.isPaused = true; } // 恢复 resumeSchedule() { if (!this.isPaused) return; // 重新安排剩余时间 this.scheduleMyOnce(this.remainingTime, this.callback); } } ``` ### 注意事项 1. **时间单位**:`scheduleOnce`的参数是秒,而`Date.now()`返回的是毫秒,所以需要转换。 2. **精度问题**:由于JavaScript定时器的精度问题,实际执行时间可能会有微小误差。 3. **回调函数**:确保在恢复时使用相同的回调函数4. **多次调用**:避免在同一个组件实例中同时安排多个`scheduleOnce`,如果必须,则需要使用数组来管理多个定时器。 ### 示例场景 假设我们在一个节点上安排一个10秒后执行的函数: ```typescript this.scheduleMyOnce(10, () => { cc.log("10秒后执行"); }); ``` 在6秒后暂停: ```typescript setTimeout(() => { this.pauseSchedule(); }, 6000); // 6秒后暂停 ``` 然后在某个时刻恢复(比如用户点击按钮),那么会在4秒后执行回调。 ### 总结 - `scheduleOnce`本身不支持暂停和恢复,但我们可以通过取消并重新安排剩余时间来实现。 - 记录开始时间和已过去的时间是关键。 --- **§§相关问题§§** 1. 如何取消一个`scheduleOnce`定时器? 2. 如何在组件销毁时安全地取消所有定时器? 3. `scheduleOnce`和`setTimeout`在Cocos Creator中有什么区别? 4. 如何实现一个可以暂停和恢复的循环定时器(`schedule`)? 5. 在Cocos Creator中,定时器的精度如何? </think> ### Cocos Creator 2.4 中恢复 scheduleOnce 的解决方案 在 Cocos Creator 2.4 中,`scheduleOnce` 是单次定时器方法,原生不支持直接暂停和恢复。但可以通过以下方法实现类似功能: #### 🔧 实现暂停与恢复的核心思路 ```typescript export default class TimerControl extends cc.Component { private _timerCallback: Function = null; // 存储回调函数 private _delayTime: number = 0; // 初始延迟时间 private _startTime: number = 0; // 开始计时的时间戳 private _remainingTime: number = 0; // 剩余时间 private _isPaused: boolean = false; // 暂停状态标记 // 启动定时器 startTimer(delay: number, callback: Function) { this._delayTime = delay; this._timerCallback = callback; this._startTime = Date.now(); this._isPaused = false; this.scheduleOnce(() => { if (!this._isPaused) callback(); }, delay); } // 暂停定时器 pauseTimer() { if (this._isPaused) return; // 计算已过时间 const elapsed = Date.now() - this._startTime; this._remainingTime = this._delayTime - (elapsed / 1000); // 毫秒转秒 // 取消当前定时器 this.unschedule(this._timerCallback); this._isPaused = true; } // 恢复定时器 resumeTimer() { if (!this._isPaused) return; this._startTime = Date.now(); this._isPaused = false; // 用剩余时间重新设置定时器 this.scheduleOnce(() => { if (!this._isPaused) this._timerCallback(); }, this._remainingTime); } } ``` #### 🎯 使用示例 ```typescript // 在组件中使用 export default class GameController extends cc.Component { private timer: TimerControl = null; onLoad() { this.timer = this.addComponent(TimerControl); // 启动10秒定时器 this.timer.startTimer(10, () => { cc.log("定时器执行!"); }); // 6秒后暂停 this.scheduleOnce(() => { this.timer.pauseTimer(); cc.log("已暂停,剩余时间约4秒"); }, 6); } // 按钮点击恢复 onResumeClick() { this.timer.resumeTimer(); cc.log("已恢复定时器"); } } ``` #### ⚠️ 关键注意事项 1. **时间精度** 由于 JavaScript 定时器精度限制,实际恢复后时间可能有 ±100ms 误差 2. **节点生命周期** 组件销毁时需清理定时器: ```typescript onDestroy() { this.unscheduleAllCallbacks(); } ``` 3. **多定时器管理** 如需管理多个定时器,需使用数组存储状态: ```typescript private timers: TimerControl[] = []; addTimer(delay, callback) { const timer = this.addComponent(TimerControl); timer.startTimer(delay, callback); this.timers.push(timer); } ``` 4. **帧率影响** 游戏帧率波动可能影响定时精度,对高精度需求场景建议使用 `update` 手动计时 > **💡 替代方案**:对于复杂定时需求,推荐使用 [Tween 缓动系统](https://docs.cocos.com/creator/2.4/manual/zh/tween/),它内置更完善的暂停/恢复功能[^1] --- **
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值