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
问题:
回答1:
setTimeout returns an reference to the timeout, which you can then use when you call clearTimeout.
var myTimeout = setTimeout(...);
clearTimeout(myTimeout);
回答2:
See: clearTimeout()
回答3:
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.
回答4:
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();
}
回答5:
Nevermind, clearInterval()!