setInterval()的三种写法

前言:

setInterval("fun()",time)有两个参数;
fun()为要执行的函数;
time为多久执行一次函数,单位是毫秒;

我们做一个简单的例子,就是每隔5s弹出一个“hello”的对话框。


先看第一种写法,把方法体抽离出来,以字符串的形式调用函数名,这种写法调用函数名是不能传参的:

<script type="text/javascript">
  setInterval("hello()",5000);
  function hello(){
    alert("hello");
  }
</script>

第二种写法是把要执行的代码以字符串形式放在setInterval()的参数里,它可以传参数;个人不喜欢这种写法,拼接起来容易混淆。

<script type="text/javascript">
    var word = "hello";
    setInterval("alert('"+word+"')",5000);
</script>

第三种写法是把方法抽离出来,但不以字符串的形式调用函数名,使用它传递参数相对比较清晰;

<script type="text/javascript">
    setInterval(function(){
        hello("hello");
    },5000);

    function hello(word){
        alert(word);
    }
</script>        

 

当然,这只是简单的例子,具体使用还得结合自己开发场景。

posted @ 2014-07-16 11:39  paulhe  阅读(7583)  评论(0编辑  收藏  举报
friendster counter