1  /**
     2   * com.sekati.time.Throttle
     3   * @version 1.0.3
     4   * @author jason m horwitz | sekati.com
     5   * Copyright (C) 2007  jason m horwitz, Sekat LLC. All Rights Reserved.
     6   * Released under the MIT License: http://www.opensource.org/licenses/mit-license.php
     7   * 
     8   * Sourced/adapted from bumpslide lib
     9   */
    10   
    11  import com.sekati.core.CoreObject;
    12  
    13  /**
    14   * Throttle time between method calls
    15   * {@code Usage:
    16   * var stageUpdater = new Throttle(Delegate.create(this, update), 500);
    17   * function onResize() { stageUpdater.trigger(); }
    18   * function doUpdate() { trace("throttled method!"); }
    19   * }
    20   */
    21  class com.sekati.time.Throttle extends CoreObject {
    22  
    23  	private var _fn:Function;
    24  	private var _delay:Number;
    25  	private var _finalInt:Number = -1;
    26  	private var _delayInt:Number = -1;
    27  	private var _isThrottled:Boolean = false;
    28  	private var _finalCallPending:Boolean = false;
    29  
    30  	/**
    31  	 * Constructor
    32  	 * @param proxyFunc (Function) Function to throttle calls to
    33  	 * @param ms (Number) millisecond delay between calls
    34  	 */
    35  	public function Throttle(proxyFunc:Function, msDelay:Number) {
    36  		super( );
    37  		_fn = proxyFunc;
    38  		_delay = msDelay;
    39  	}
    40  
    41  	/**
    42  	 * trigger call to method
    43  	 */
    44  	public function trigger():Void {	
    45  		clearInterval( _finalInt );	
    46  		if(_isThrottled) {
    47  			//trace('[Throttle] Forcing Wait...');
    48  			_finalCallPending = true;
    49  			return;
    50  		} else {
    51  			_doFunctionCall( );
    52  			_finalCallPending = false;
    53  			_isThrottled = true;		
    54  			clearInterval( _delayInt );
    55  			_delayInt = setInterval( this, "clearThrottle", _delay );
    56  		}
    57  	}
    58  
    59  	/**
    60  	 * clear throttling
    61  	 */
    62  	public function clearThrottle():Void {
    63  		clearInterval( _delayInt );		
    64  		_isThrottled = false;
    65  		if(_finalCallPending) {
    66  			//trace('[Throttle] Doing Final Call...');
    67  			_doFunctionCall( );
    68  		}
    69  	}
    70  
    71  	private function _doFunctionCall():Void {
    72  		//trace('[Throttle] Calling Function at '+getTimer());
    73  		_finalCallPending = false;
    74  		_fn.call( null );		
    75  	}
    76  
    77  	/**
    78  	 * Destroy instance.
    79  	 */
    80  	public function destroy():Void {
    81  		clearThrottle( );
    82  		super.destroy( );
    83  	}	
    84  }