鸟食轩

 Microsoft .NET[C#] MVP 2003
随笔 - 424, 文章 - 231, 评论 - 5394, 引用 - 344
数据加载中……

使用匿名函数为setInterval传递参数

    在使用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。

posted on 2006-01-08 00:18 birdshome 阅读(2948) 评论(3)  编辑 收藏 所属分类: Jscript&Dhtml开发

评论

#1楼    回复  引用    

//以下是我测试的一个程序:
<head>
<title>SetInterval Page</title>
<script language=javascript type="text/javascript">
function show()
{
var ev = event;

showInterval(ev);
}

function showInterval(e)
{
//alert(e.type)
window.setInterval(function()
{
alert(e.type)
},1000)
}

</script>
</head>
<body>
<input id="Button1" style="width: 300px; height: 74px" type="button" value="button" onmousemove="show()"/>

</body>
</html>

//发现当把alert(e.type)放进setInterval里的匿名函数之后,e的属性值竟然
//丢失了,运行不出alert(e.type),不知是何原因,请指教!!!!
2006-05-12 15:22 | 冰逸 [未注册用户]

#2楼 [楼主]   回复  引用  查看    

@冰逸
你那个写错了,而且event对象里的内容是有时效的,就是说如果当前事件结束,event自动就被清空了。正确的应该是:
<html>
    
<head>
        
<title>SetInterval Page</title>
        
<script language="javascript" type="text/javascript"> 
            
function show() 
            

                
var type = event.type; 
                showInterval(type); 
            }
 
            
function showInterval(type) 
            

                
var foo = function() 
                
{
                    
var type = foo.type;
                    alert(type) 
                }
;
                foo.type 
= type;
                window.setTimeout(foo, 
1000);
            }
 
        
</script>
    
</head>
    
<body>
        
<input id="Button1" style="width: 300px; height: 74px" type="button" value="button" onmousemove="show()"
            NAME
="Button1" />
    
</body>
</html>
2006-05-12 18:55 | birdshome      

#3楼    回复  引用    

jia 我QQloveyouwangsu@126.com ~~~~~~~
2007-10-14 21:01 | 王苏 [未注册用户]