how to write something like setTimeout

A

Antony Sequeira

Hi
While looking at some code I realized that the built in
setTimeout
function takes a string that is later
evaluated in the original caller's context.
How does one achieve something similar in user defined functions.

-Antony
 
L

Lee

Antony Sequeira said:
Hi
While looking at some code I realized that the built in
setTimeout
function takes a string that is later
evaluated in the original caller's context.
How does one achieve something similar in user defined functions.

You use setTimeout.
In other words, your question isn't clear.
Why won't setTimeout do what you want?
 
Y

Yann-Erwan Perio

Antony said:
While looking at some code I realized that the built in
setTimeout
function takes a string that is later
evaluated in the original caller's context.

This original context is always the global object (window). However, you
can perfectly use a function reference or a function expression instead
of a string as the first argument for setTimeout - this isn't supported
by old browsers though, which would then call the toString() method for
the function while evaluating the setTimeout first argument - test
accordingly.

function foo(){
var bar="hello, world!";
setTimeout(
function(){
alert(bar);
},
1000
);
}

Using a function expression is much more powerful than using a string
argument, since you can control the scope chain and add a specific scope
object, just for this function (either using an outer function or a
"with" statement).

---
setTimeout(
(function(){
var foo=0, bar=0;
return function(){
window.status="foo:"+foo+", bar:"+bar;
if(foo++<1000 && bar-->-1000)
setTimeout(arguments.callee, 50);
}
})(),
50
);
---


---
with({foo:0,bar:0}){
setTimeout(
function(){
window.status="foo:"+foo+", bar:"+bar;
if(foo++<1000 && bar-->-1000)
setTimeout(arguments.callee, 50);
},
50
);
}
 
A

Antony Sequeira

Yann-Erwan Perio said:
This original context is always the global object (window).
Ok. Thanks for correcting my mis-conception and for the example code.
-Antony
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top