setTimeout参数

setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式。
setTimeout(code,millisec)
code:要调用的函数后要执行的 JavaScript 代码串。
millisec:在执行代码前需等待的毫秒数。

1.将函数名称作为调用句柄(直接调用函数名称):

function hello(){
       alert("hello");
}
setTimeout(hello,3000);

这里不能写成setTimeout(hello(),3000);,这样为立即执行调用。
但是可以setTimeout("hello()",3000);,这里hello()其实就是所谓的JavaScript 代码串。
2、函数带参数:

var userName="jack";
function hello(name){
       alert("hello,"+name);
}
setTimeout('hello(userName)',3000);

这里必须用'',不能写成setTimeout(hello(userName),3000);,不然会立即执行调用。
但这种写法不够直观,而且有些场合必须使用函数名,下面用一个小技巧来实现带参数函数的调用:

<script language="JavaScript" type="text/javascript">
var userName="jack";
//根据用户名显示欢迎信息
function hello(_name){
       alert("hello,"+_name);
}
//创建一个函数,用于返回一个无参数函数
function _hello(_name){
       return function(){
             hello(_name);
       }
}
setTimeout(_hello(userName),3000);
</script>

这里定义了一个函数_hello,用于接收一个参数,并返回一个不带参数的函数,在这个函数内部使用了

外部函数的参数,从而对其调用,不需要使用参数。在setTimeout函数中,使用_hello(userName)来返回一个不带参数的函数句柄,从而实现了参数传递的功能。

3.案例

function moveElement(elementID,final_x,final_y,interval){
    if (!document.getElementById) return true;
    if (!document.getElementById("elementID")) return false;
    var elem = getElementById("elementID");
    var xpos = parseIn(elem.style.left);
    var ypos = parseIn(elem.style.top);
    if (xpos == final_x && ypos == final_y){
        return true;
    }
    if (xpos < final_x){
        xpos++ ;
    }
    if (xpos > final_x){
        xpos --;
    }
    if (ypos < final_y){
        ypos ++;
    }
    if (ypos > final_y){
        ypos --;
    }
    elem.style.left = xpos + "px";
    elem.style.top = ypos + "px";
    var repeat = "moveElement('"+elementID+"',"+final_x+","+final_y+","+interval+")";
    movement = setTimeout(repeat,interval);
}

另。setTimeout运行方式案例详见:http://www.2cto.com/kf/201408/328410.html

原文地址:https://www.cnblogs.com/wjx91/p/6476786.html