settimeout problem

G

Gordan

hi

i want to have a "close" button that user can click but that will also
"click itself after 10 sec"
so heres what i did

function auto_close(x)
{
if(x>0){ document.form.button.value="CLOSE (auto close in "+ x +" sec)";
x--;
setTimeout("auto_close(x);",1000);
} else self.close();
}

and i put onload=auto_close(10)

the problem is that the first time the recursion is called (
setTimeout("auto_close(x);",1000);) IE says x is undifined
i dont understand!!

please help, Gordan
 
D

Douglas Crockford

i want to have a "close" button that user can click but that will also
"click itself after 10 sec"
function auto_close(x)
{
if (x > 0){ document.form.button.value="CLOSE (auto close in "+ x +" sec)";
x--;
setTimeout("auto_close(x);", 1000);
} else self.close();
}

and i put onload = auto_close(10);

the problem is that the first time the recursion is called (
setTimeout("auto_close(x);",1000);) IE says x is undifined

x is a local var of auto_close. When setTimeout finally evaluates the string, it
is not inside of auto_close, so the value of x is not available.

You can get around this by passing a function instead.

setTimeout(function () {
auto_close(x);
}, 1000);

Static binding gives that function access to x.

http://www.crockford.com/javascript/inheritance.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top