Reputation: 4617
I'm trying to call an instance's method with a delay of 750ms. The problem is, it doesn't work. I've read that there's some sort of problem with setInterval and objects so probably there's one with setTimeout as well.
Say I have this:
function App()
{
this.doFoo = function (arg)
{
alert("bar");
}
}
window.app = new App();
setTimeout('app.doFoo(arg)', 750);//doesn't work
app.doFoo(arg); //works
Is there a workaround? How do I go about passing the instance and function to setTimeout?
Upvotes: 1
Views: 446
Reputation: 61
i think the previous answer needs a little tweak. it is setting a global variable that you are then calling; if you really want to call an instance of your 'class' try this.
function App(message){
this.name = 'instance';
var self = this;
var x = setTimeout(function(){self.doFoo(message, x);}, 750);
}
App.prototype.name = 'proto';
//creating the function on the prototype is more efficient since it is only created once. if you do 'this.doFoo = function(){}' it's created for every instance of the function taking more memory.
App.prototype.doFoo = function(arg, timer){
clearTimeout(timer);
alert(this.name +' ' + arg)
}
var x = new App("hello world");
//should output ("instance hello world");
Upvotes: 2
Reputation: 1038730
Try like this:
function App()
{
this.doFoo = function (arg) {
alert(arg);
}
}
window.app = new App();
window.setTimeout(function() {
window.app.doFoo('arg');
}, 750);
Upvotes: 2