Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

setTimeout ... how to save context?

Status
Not open for further replies.

maremic

Programmer
Mar 30, 2009
1
RO
<html>

<head>
<script type="text/javascript">
function test() {
for (var i=0; i<10; i++) {
setTimeout( function() {
alert("execution " + i)
}, 1000 )
}
}

test()

</script>
</head>


<body>

</body>

<html>


I am searching for a way to delay a function's execution;
the problem is a bit more complex but it can be resumed to
the inline function I wrote in this example.

I need to delay a function with some seconds, but I can not
manage to save the context and so when the function is
called, the delayed action only applies to the last element
(here only alerts "execution 10" instead of "execution
0"... "execution 1" ... etc).

 
Hi

Ugly solution, but I used to do it with string :
Code:
function test()
{
  for (var i=0; i<10; i++) {
    setTimeout('alert("execution " + '+i+')',1000)
  }
}

test()

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top