setInterval 传值 设参数

来源:互联网 发布:ubuntu 开机脚本 编辑:程序博客网 时间:2024/05/18 17:23
<script type="text/javascript" >window.onload=function(){for(var i=1;i<3;i++){var m ="i="+i;setInterval(function(){test(m);},4000);}}function test(e) {alert(e);}</script>

上面这段代码的运行结果是:

alert 只弹出i=2;

这样的结果给人一种好像只创建了一个setInterval方法或者说是定时器吧.其实如果你自己看还是会发现有时弹出的对话框是连续的两个对话框的,所以这个程序说明for循环中是初始化了两个计时器的.只不过是因为变量的问题所以产生了这种奇异的现象.

原因是setInterval这个计数器是在延迟4秒后才进行调用,而在这期间for循环还是会继续运行的,那么当setInterval执行时i的值已经变成2了;

<script type="text/javascript" >window.onload=function(){for(var i=1;i<3;i++){setInterval(function(){test(i);},4000);}}function test(e) {alert(e);}</script>
那么上面这个alert的值却是3;这也就是说i传到setInterval这个计数器中的function参数是3,这个也是因为延迟的问题,当for循环执行完时i的值是3<因为i++了>

那么如何处理这种问题了:

这是一段代码:

<html><head><script type="text/javascript">function intervalTest(){var cks = document.getElementsByName("check");for(var i=0;i<cks.length;i++){if(cks[i].checked == true){mySetInterval(test,(3-i)*1000,i);}}}function test(e) {console.log(e);}function mySetInterval(f,time,param){setInterval(function(){f(param);},time);}</script></head><body><input name="check" type="checkbox" id="1"/>OneCheck<input name="check" type="checkbox" id="2"/>TwoCheck<input name="check" type="checkbox" id="3"/>ThreeCheck<input type="button" onclick="intervalTest()" value="IntervalTest"/></body></html>
上面主要是写了一个自己的方法mySetInterval(f,time,param)其中f为回调函数的名称,time为设置的间隔时间,param为f函数的参数值.

这样写的意思就是说当你在循环的时候就直接先调用我的这个方法,然后把参数传给我,然后你在进行for循环,这样就保证了每次传入的值不会在延迟time后而变化.