当前位置: 首页 > 图文教程 > 网络编程 > Javascript > Javascript 定时器调用传递参数的方法

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 定时器调用传递参数的方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 359 ::
收藏到网摘: n/a

Javascript 定时器调用传递参数的方法,需要的朋友可以参考下。 无论是window.setTimeout 还是window.setInterval,在使用函数名作为调用句柄时都不能带参数,而在许多场合必需要带参数,这就需要想方法解决.
例如对于函数hello(_name),它用于针对用户名显示欢迎信息:
复制代码 代码如下:

var userName="Tony";
//根据用户名显示欢迎信息
function hello(_name){
alert("hello,"+_name);
}

这时,如果企图使用以下语句来使hello函数延迟3 秒执行是不可行的:
window.setTimeout(hello(userName),3000);
这将使hello函数立即执行,并将返回值作为调用句柄传递给setTimeout 函数,其结果并不是程序需要的.而使用字符串形式可以达到想要的结果:
window.setTimeout("hello(userName)",3000);
这里的字符串是一段JavaScript 代码,其中的userName 表示的是变量.但这种写法不够直观,而且有些场合必须使用函数名,下面用一个小技巧来实现带参数函数的调用:
复制代码 代码如下:

<script language="JavaScript" type="text/javascript">
<!--
var userName="jack";
//根据用户名显示欢迎信息
function hello(_name){
alert("hello,"+_name);
}
//创建一个函数,用于返回一个无参数函数
function _hello(_name){
return function(){
hello(_name);
}
}
window.setTimeout(_hello(userName),3000);
//此处也可以写为window.setTimeout( function(){return hello(userName)}, 3000);
//就不用再定义function _hello()
//-->
</script>

这里定义了一个函数_hello,用于接收一个参数,并返回一个不带参数的函数,在这个函数内部使用了外部函数的参数,从而对其调用,不需要使用参数.在window.setTimeout函数中,使用_hello(userName)来返回一个不带参数的函数句柄,从而实现了参数传递的功能.