[osflash] clearInterval quandry

Rákos Attila tenegri at tengerstudio.com
Fri Nov 11 23:01:01 EST 2005


Actually, it will not work, since while your doSomething() is running
the "this" reference is empty (undefined). And also the argument list of
setInterval() is not correct, because your first parameter simply doesn't
exist. However it will work with a little modification:

     public function beginInterval():Void {
         var obj:Object = new Object();
         obj.thisRef = this;
         obj.id = setInterval(doSomething, 200, obj);
     }
     
     public function doSomething(obj:Object):Void {
         trace("doSomething called with: " + obj.id);
         obj.thisRef.doSomethingElse();
         clearInterval(obj.id);
     }

     public function doSomethingElse():Void {
         trace("doSomethingElse called");
     }

Or even we can make it better and create a reusable method, where the
call to doSomethingElse() is not hardcoded:

class IntervalManager {
  static public function setTimeout(aParentObj: Object, aFunction: Function, aInterval: Number, aParam: Object): Number {
    var obj: Object = {parent: aParentObj, func: aFunction, param: aParam};
    obj.id = setInterval(callTimeoutFunc, aInterval, obj);
    return obj.id;
  }
  
  static private function callTimeoutFunc(aObj: Object): Void {
    aObj.func.call(aObj.parent, aObj.param);
    clearInterval(aObj.id);
  }
}

class myClass {
  public function beginInterval(Void): Void {
    IntervalManager.setTimeout(this, doSomething, 200, "Hello world!");
  }
    
  public function doSomething(aText: String): Void {
    trace("doSomething() is called with parameter '" + aText + "'");
  }
}
 
  Attila

LB> The single best method I have seen for managing intervals is to storethe intervalId in a new object, then pass a reference of that object tothe interval handler as an argument.
LB> 
LB> With this, you don't clutter up your classes with interval managementmember variables, the called method can execute code in the scope ofwhere it is declared. and then simply clear the interval whenever itwants to...
LB> 
LB>     public function beginInterval():Void {
LB>         var obj:Object = new Object();
LB>         obj.id = setInterval(this, "doSomething", 200, obj);
LB>     }
LB>     
LB>     public function doSomething(obj:Object):Void {
LB>         trace("doSomething called with: " + obj.id);
LB>         this.doSomethingElse();
LB>         clearInterval(obj.id);
LB>     }
LB> 
LB>     public function doSomethingElse():Void {
LB>         trace("doSomethingElse called");
LB>     }
LB> 
LB> 
LB> I haven't tested the code - but it should work...
LB> 
LB> 
LB> Good Luck,
LB> 
LB> Luke Bayes
LB> www.asunit.com





More information about the osflash mailing list