是否有任何方法可以在ActionScript中实现等待3秒,但是保持在同一个函数中?我看过setInterval,setTimeOut和类似的函数,但我真正需要的是:
public function foo(param1, param2, param3) { //do something here //wait for 3 seconds //3 seconds have passed, now do something more }
万一你想知道为什么我需要这个 - 这是一个法律要求,不,我不能改变它.
使用Timer
3秒后调用一个函数.
var timer:Timer = new Timer(3000); timer.addEventListener(TimerEvent.TIMER, callback); // will call callback() timer.start();
要正确执行此操作,您应该将计时器创建为实例变量,以便在调用函数时删除侦听器和计时器实例,以避免泄漏.
class Test { private var timer:Timer = new Timer(3000); public function foo(param1:int, param2:int, param3:int):void { // do something here timer.addEventListener(TimerEvent.TIMER, fooPartTwo); timer.start(); } private function fooPartTwo(event:TimerEvent):void { timer.removeEventListener(TimerEvent.TIMER, fooPartTwo); timer = null; // 3 seconds have passed, now do something more } }
您还可以在函数内使用另一个函数foo
并保留范围,因此您不需要传递变量.
function foo(param1:int, param2:int, param3:int):void { var x:int = 2; // you can use variables as you would normally // do something here var timer:Timer = new Timer(3000); var afterWaiting:Function = function(event:TimerEvent):void { timer.removeEventListener(TimerEvent.TIMER, afterWaiting); timer = null; // 3 seconds have passed, now do something more // the scope is retained and you can still refer to the variables you // used earlier x += 2; } timer.addEventListener(TimerEvent.TIMER, afterWaiting); timer.start(); }