setTimeout将参数传递给函数 [英] setTimeout passing parameters to a function

查看:100
本文介绍了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

推荐答案

Jamal,您为什么不更改为以下代码:
Hi Jamal, why don''t you change to code below:
var count = 0;
function foo()
{
  if (count<5)
  {
    alert(count);
    count++;
    var result = setTimeout("foo()",100);
  }
}
foo();




在您的示例中,setTimeout的回调函数是一个匿名函数.因此,变量i的范围不再像您期望的那样.当回调函数被调用时,i的值将来自foo()函数,在那一刻循环完成,这意味着该值为5.您可以在google上搜索这些内容.


Robby Tendean615解决方案很棒.
Hi,

In your example, the callback function of setTimeout is an anonymous function. Because of this, the scope of variable i, is no longer as you expected. When the callback function is invoked, value of i it will be from the foo() function, and in that moment the loop is done and these means the value is 5. You can search on google about these things.


Robby Tendean615 solution is great.


我找到了解决方案.

效果很好:
I found the solution.

It works very well:
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将参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆