0

I see that there are some other questions that seem to be on a similar topic but none have an answer that will help me with my particular problem. I have made a thread library in in JavaScript built around the setTimeout and setInterval functions. This is working very well except that my thread library requires that the name of thread is past to the thread i.e when I instantiate the thread it looks like this.

t = new Thread(payload, "t") 

payload is an object that defines the what the thread will do when it gets a chance to execute. This allows me to abstract the task of the thread from the underlying threads "plumbing". In any case my problem that I have to pass name of thread because setTimeout and setInterval take a JavaScript command as a string i.e setTimeout("doStuff", 0). As I use my thread library in more applications passing the name to the thread is becoming more of a pain. So I would like to be able to avoid this by getting the name of the thread from within the thread class like this:

var myThreadName = this.someMagicFunction(); 

or

var myThreadName = someMagicFunction(this); 

or some other fantastic method if anyone has any ideas for me I would be most grateful.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Overfloater
  • 761
  • 1
  • 5
  • 7

2 Answers2

3

Actually, both can take a function as the first parameter, and this is the recommended usage (since the string versions do an eval).

setTimeout(doStuff, 0);

In your case, you might be able to do something like:

setTimeout(function(){
  t.payload();
}, 0);

depending how the Thread object looks.

See the MDC documentation (setTimeout, setInterval).

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • thanks for the help it worked like a charm. I was running into trouble before because I was doing setTimeout(doStuff(),1). Passing the function by name works perfectly. Once again thanks for the help. – Overfloater Oct 22 '11 at 08:53
0

You can pass a function to setTimeout as long as it is argument-free, i.e.

function takeme()
{
    alert('workin?');
}

setTimeout(takeme, 100);

and if it is not, then you can try

function takeme(x)
{
    alert(x);
}
var test = 1;
setTimeout(function(){ takeme(test); }, 100);

But if you really need to extract a function name, then please see this post. Not exactly the same, but somewhat related.

Community
  • 1
  • 1
freakish
  • 54,167
  • 9
  • 132
  • 169