当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 精解window.setTimeout()&window.setInterval()使用方式与参数传递问题!

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 中的 精解window.setTimeout()&window.setInterval()使用方式与参数传递问题!


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 184 ::
收藏到网摘: n/a

在使用JScript的时候,我们有时需要间隔的执行一个方法,比如用来产生网页UI动画特效啥的。这是我们常常会使用方法setInterval或setTimeout,但是由于这两个方法是由脚本宿主模拟出来的Timer线程,在通过其调用我们的方法是不能为其传递参数。
我们常用的使用场景是:
复制代码 代码如下:

window.setTimeout("delayRun()", n);
window.setInterval("intervalRun()", n);
window.setTimeout(delayRun, n);
window.setInterval(intervalRun, n);

显然强行代参数的调用: window.setTimeout("delayRun(param)", n);
复制代码 代码如下:

window.setInterval("intervalRun(param)", n);
window.setTimeout(delayRun(param), n);
window.setInterval(intervalRun(param), n);

都是错误的,因为string literals形式的方法调用,param必须是全局变量(即window对象上的变量)才行;而function pointer形式的调用,完全错误了,这是把函数的返回值当成了setTimeout/setInterval函数的参数了,完全不是我们所望的事情。
解决这个问题的办法可以使用匿名函数包装的方式,在以下scenario中我们这么做:
复制代码 代码如下:

function foo()
{
var param = 100;
window.setInterval(function()
{
intervalRun(param);
}, 888);
}
function interalRun(times)
{
// todo: depend on times parameter
}
这样一来,就可以不再依赖于全局变量向delayRun/intervalRun函数中传递参数,毕竟当页面中的全局变量多了以后,会给脚本的开发、调试和管理等带来极大的puzzle。