how to kill a setTimeout() function

2019-02-24 08:41发布

I use the setTimeout() function through my application but when its time to garbage collect. the method still runs and calls on a function. How do I stop it from calling on a certain function. I tried setting it to null but it doesnt work

5条回答
做自己的国王
2楼-- · 2019-02-24 08:52

Nevermind, clearInterval()!

查看更多
放我归山
3楼-- · 2019-02-24 09:10

setTimeout returns an reference to the timeout, which you can then use when you call clearTimeout.

var myTimeout = setTimeout(...);
clearTimeout(myTimeout);
查看更多
Melony?
4楼-- · 2019-02-24 09:13

I had a similar situation and it drove me crazy for a couple of hours. The answers I found on the net didn't help either but eventually I found that calling System.gc() does the trick.

I use a weak reference ENTER_FRAME listener to test if the instance gets removed by the GC. If the GC clears the object the ENTER_FRAME should stop running.

Here is the example:

package {

import flash.display.Sprite;
import flash.events.Event;
import flash.system.System;
import flash.utils.getTimer;
import flash.utils.setTimeout;

public class GCTest {
    private var _sprite:Sprite;

    public function GCTest():void {
        this._sprite = new Sprite();
        this._sprite.addEventListener(Event.ENTER_FRAME, this.test, false, 0, true);
        setTimeout(this.destroy, 1000); //TEST  doesn't work
    }

    private function test(event:Event):void {
        trace("_" + getTimer());    //still in mem
    }

    public function destroy():void {
        trace("DESTROY")
        System.gc();
    }

}}

When you comment out System.gc(); the test method keeps getting called even after the destroy method was called (so the timeout is done). This is probably beacause there is still enough memory so the GC doesn't kick in by it self. When you comment out the setTimeout the test method won't be called at all meaning the setTimeout is definitely the problem.

Calling the System.gc(); will stop the ENTER_FRAME from dispatching.

I also did some tests with clearTimeout, setInterval and clearInterval but that had no effect on the GC.

Hope this helps some of you with the same or similar problems.

查看更多
趁早两清
5楼-- · 2019-02-24 09:17

See: clearTimeout()

查看更多
Evening l夕情丶
6楼-- · 2019-02-24 09:17

Ditto. Use "clearInterval(timeoutInstance)".

If you are using AS3, I'd use the Timer() class

import flash.utils.*;
var myTimer:Timer = new Timer(500);
myTimer.addEventListener("timer", timedFunction);

// Start the timer
myTimer.start();

function timedFunction(e:TimerEvent)
{
  //Stop timer
  e.target.stop();
}
查看更多
登录 后发表回答