Click here to Skip to main content
15,886,422 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.


JavaScript
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
}

thanks in advance.

Regards Jamal
Posted
Updated 28-May-23 22:59pm
v3
Comments
Dalek Dave 10-Jan-12 4:09am    
Edited for Readability.

Hi Jamal, why don't you change to code below:
JavaScript
var count = 0;
function foo()
{
  if (count<5)
  {
    alert(count);
    count++;
    var result = setTimeout("foo()",100);
  }
}
foo();
 
Share this answer
 
Comments
Jamal Seyedi 10-Jan-12 3:17am    
thnaks for answring me.
I found the logical way.
We should use clousers in javascript.
Jamal Seyedi 10-Jan-12 3:20am    
I mean closures
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.
 
Share this answer
 
Comments
Jamal Seyedi 10-Jan-12 3:27am    
thanks, now I found the solution, scope parameters are secret. take a look at solution 3.
I think now I understand what to do.
I found the solution.

It works very well:
C#
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
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900