Javascript:为什么我可以't清除我的对象行为中的超时

Javascript: Why I can't clearTimeout in my object behavior?

本文关键字:对象 我的 超时 清除 为什么 我可以 Javascript      更新时间:2023-09-26

我已经解决了很多小时,但我不知道为什么我不能解决它。我有以下代码:

var Timer_Tick;
var Game_Engine = {
    //Set the min and sec of the timer by default is 2 min
    min:1,
    sec:60,
    star_count: 0,
    tongue_count: 0,
    time: '',
    star1: '',
    star2: '',
    star3: '',
    star_bar: '',
    tongue_bar: '',
    frog: '',
    bug: '',
    flower: '',
    Timer: function () {
        //Start Timer
        var that = this;
        var stop = function () { that.stopTimer(); };
        Timer_Tick = setTimeout(function () {
                var Time = new Date(0, 0, 0, 0, that.min, that.sec--).toTimeString().slice(3,8);
                that.time.text = Time;
                console.log(that.min + ':' + that.sec);
                    if (that.min === 1 && that.sec === 40) {
                        that.bug.gotoAndPlay('take_photo');
                        that.flower.onPress = null;
                        stop();
                    }
                    else if (that.min === 1 && that.sec === -60) {
                        that.stopTimer();
                        //clearTimeout(Timer_Tick);
                        that.time.text = '00:00';
                        createjs.Tween.get(that.bug, { loop: false }).to({ y: that.bug.y + 100 }, 400, createjs.Ease.linear);
                        setTimeout(function () {
                            that.bug.gotoAndPlay('bite');
                            setTimeout(function () {
                                that.flower.gotoAndPlay('broken_flower');
                                that.frog.gotoAndPlay('lose');
                            }, 200);
                            createjs.Tween.get(that.bug, { loop: false }).wait(500).to({ x: 200, y: -100 }, 6000, createjs.Ease.linear);
                        }, 400);
                    }
                that.Timer();        
        }, 100);
    },
    stopTimer: function () {
        //Pause or stop Timer
        clearTimeout(Timer_Tick);
    }
};

我已经放置了debugger,以确定我的事件是否被触发。结果是,它按预期正确启动,但计时器不会停止并永远运行。有人能帮我吗?我现在真的需要你的帮助。我是javascript的新手:)。提前感谢。

在计时器函数中调用stop后,尝试添加"return false;"。现在我想你会停止定时器,但你会在函数的底部再次启动它。

if (that.min === 1 && that.sec === 40) {
   that.bug.gotoAndPlay('take_photo');
   that.flower.onPress = null;
   stop();
   return false;
}