Jinu Joseph Daniel
Jinu Joseph Daniel

Reputation: 6291

Passing local functions to setTimeout()

I have written the following function.

function obj()
{
     this.a;
}
obj.prototype.catch = function()
{
    alert('Catched')
}
obj.prototype.do = function()
{
    alert('called');
}

What i need is, to call obj::catch() after obj::do() is called and the call must be performed from inside obj::do() So how to pass the local function of obj to setTimeout

i have tried

obj.prototype.do = function()
 { 
     window.setTimeout('"'+this.catch+'()"',1000);
     alert('called');
 }

It does not worked Then i tried

 obj.prototype.do = function()
 { 
     window.setTimeout('"'+this+'.catch()"',1000);
     alert('called');
 }

which gave me the following error on Chrome console

Uncaught SyntaxError: Unexpected token ILLEGAL

So i tried the following dirty method(is it really dirty ?)

 obj.prototype.do = function()
 { 
     this.pid = randomVal(100);
     window['temp'+this.pid] = this;
     window.setTimeout("temp"+this.pid+".catch();",1000);
     alert('called');
 }
 function randomVal(bound)//returns a random number between 0 and <bound>
 {
       return (Math.floor(Math.random()*(bound)));
 }

That worked.

so why the first two methods not worked.Is there any other way to do the same thing without global variables.. The second method and last method are almost similar .But why am i gettng the error in second method..? The worked code can be found here http://jsfiddle.net/jXhAs/

Upvotes: 3

Views: 2464

Answers (4)

rlemon
rlemon

Reputation: 17667

Why go through all of this effort, just pass the function.

function obj() {
    this.a;
}
obj.prototype.
catch = function() {
    alert('Catched')
}
obj.prototype.do = function() {
    setTimeout(this.
    catch, 1000);
}

var test = new obj();
test.do();​

Upvotes: 0

Quentin
Quentin

Reputation: 944205

Don't pass strings to setTimeout … ever.

var self = this; // Because the scope will change
setTimeout(function () { self.catch() },1000);

Or if you are using JS 1.8.5:

setTimeout(this.catch.bind(this),1000);

You can read more about bind

Upvotes: 8

Naftali
Naftali

Reputation: 146340

You should pass a function to setTimeout (not a string):

Example:

var self = this;
setTimeout(function(){
    self.catch();
},1000);

Upvotes: 5

micha
micha

Reputation: 1085

use a closure

obj.prototype.do = function()
{ 
     window.setTimeout((function(that){
        return function(){
            that.catch();
        };
     })(this),1000);
     alert('called');
}

Upvotes: 1

Related Questions