本文介绍了setTimeout将参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环,我想在其中使用setTimeout调用一个函数并传递一些参数.

该函数被调用5次,但是每次arg1等于(5)时,参数都不是我期望的.

我期望的是,第一次调用该函数,第二次调用arg1 = 1以Arg1 = 4结尾时,arg1 =0.

我每次都得到(arg1 = 5).


I have a loop in which I want to call a function with setTimeout and pass some arguments.

The function is called 5 times but the argument is not what I expect,in each time the arg1 equals(5).

What I expect is getting arg1= 0 when the function is called for the first time and the second time arg1=1 ending with Arg1 = 4.

What I get is (arg1=5) each time.


foo();
function foo()
{
	for (var i = 0; i < 5; i++)
	{
		setTimeout(
		function(){
		callingByTimeout(i)
		}
		,100)
	}
}
function callingByTimeout(arg1)
{
	alert(arg1)
	//output for first time  : 5
	//output for second time : 5
	//output for third time  : 5
	//output for fourth time : 5
	//output for fifth time  : 5
}


在此先感谢.

关于Jamal


thanks in advance.

Regards Jamal

推荐答案

var count = 0;
function foo()
{
  if (count<5)
  {
    alert(count);
    count++;
    var result = setTimeout("foo()",100);
  }
}
foo();



foo();
function foo(i)
{
    for (var i = 0; i < 5; i++)
    {
        setTimeout(
        function (index)
        {
            return function ()
            {
                callingByTimeout(index);
            }

        } (i)
        , 1000)
    }
}
function callingByTimeout(arg1)
{
    alert(arg1)
    //output for first time  : 0
    //output for second time : 1
    //output for third time  : 2
    //output for fourth time : 3
    //output for fifth time  : 4
}


这篇关于setTimeout将参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:08
查看更多