【永恒的瞬间】
☜Give me hapy ☞

setInterval 函数是Action Script 的全局函数,在Action Script 3.0 中它 被封装在 flash.util 包中,详见http://livedocs.macromedia.com/labs/1/flex/langref/migration.html, 它需要flash player 6 或以上版本的支持。

setInterval 有两种用法:
1.  setInterval(functionName:Function, interval:Number [, param1:Object, param2, ...,paramN]) : Number
这种使用方法是让flash player 每隔interval (ms)时间调用functionName()这个函数,不关心这个方法是哪个对象的,后面跟传入的参数;一般来说这些参数值用来为函数提供数据,而不是从函数里取出数据。

2.  setInterval(obj:Object, methodName:Function, interval:Number [, param1:Object, param2, ...,paramN]) : Number
这种方法调用obj 对象中的成员方法methodName,在flex 应用中必须使用这样的方法来实现定时调用的效果。这样的方式就能够,在methodName中就能够访问当前flex application的 成员变量或函数了。举个例子:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application  initialize="initFunc()" xmlns:mx="http://www.macromedia.com/2003/mxml">
 <mx:Script>
 <![CDATA[
  var count:Number;
  function initFunc()
  {
   count = 60;
   setInterval(this, "countDown", 1000);
  }
  
  function countDown()
  {
   showLabel.text = count.toString() + "second to go";
   count -= 1;
   if(count == 0)
    timeUp();
  }
  
  function timeUp()
  {
   alert("Time is up");
  }
 ]]>
 </mx:Script>
 <mx:Label id="showLabel"/>
</mx:Application>

如果这里使用第一种方法的话 就会出现 countDown 函数不能访问到count 和 showLabel 这两个变量,功能就没法实现,虽然可以通过传参数的方法来传入count 和 label:
setInterval(countDown, 1000, count:Number, showLabel:mx.controls.Label);
但是这样话 count-=1 并不起作用,所以根本不会count down。这个搞了我好久,开始没有看到第二种用法,大家要留意。

好看一点的例子:

 function init()
 {

  var spanSec:Number=60*60 //an hour to go
  var nf:mx.formatter.NumberFormatter = new mx.formatters.NumberFormatter();
  nf.precision = 0;
  nf.rounding = "down";
 }

 function timeCountDown()
 {
  var hr:Number =parseInt(nf.format(spanSec/3600));
  var min:Number = parseInt(nf.format((spanSec - hr*3600)/60));
  var sec:Number = parseInt(nf.format(spanSec - 60*min - hr*3600));
  spanSec = spanSec - 1;
  countDownLabel.text="Time left: "+hr+":"+min+":"+sec; 
  if(spanSec == 0)
  {
   submit();
  }
  
 }

 function submit()
 {
    //do whatever you want
 }

posted on 2007-01-12 15:44 ☜♥☞MengChuChen 阅读(769) 评论(0)  编辑  收藏 所属分类: flex2.0

只有注册用户登录后才能发表评论。


网站导航: