I want to call editObject() inside of my jQuery function, the initalisation call does work, but setTimeout doesn't work, how to get it running? Console says that editObject is not defined when called by setTimeout:
(function($){
$.fn.extend({
...
editObject()
function editObject() {
alert("Test!");
setTimeout('editObject()', 1000);
}
return this.each(function() {
var o = options;
});
}
});
})(jQuery);
Thanks for help!
I want to call editObject() inside of my jQuery function, the initalisation call does work, but setTimeout doesn't work, how to get it running? Console says that editObject is not defined when called by setTimeout:
(function($){
$.fn.extend({
...
editObject()
function editObject() {
alert("Test!");
setTimeout('editObject()', 1000);
}
return this.each(function() {
var o = options;
});
}
});
})(jQuery);
Thanks for help!
Share Improve this question asked Jan 7, 2011 at 16:08 Pascal BayerPascal Bayer 2,6138 gold badges33 silver badges51 bronze badges5 Answers
Reset to default 8It doesn't work because editObject() is declared in the scope of your anonymous function, but setTimeout() evals the string you passed it in a global context. Try this:
setTimeout(editObject, 1000);
You could try this:
setTimeout(function(){ editObject.call() }, 1000);
Or:
setTimeout(arguments.callee, 1000);
You should avoid using the string version of setTimeout
.
I believe that, in this case, Javascript is looking for the function window.editObject
and this does not exist.
You should use:
setTimeout(editObject,1000);
instead, as this is grabbing a reference to the object at call-time and so the function will be available to Javascript, for calling, when the timeout expires
Use the function reference directly (rather than a string, which is evaluated in a global context), like this:
setTimeout(editObject, 1000);
UPDATE: I certainly misunderstood the problem, my original code edited to be working:
var foo = function () {
var that = this;
that.editObject = function() {
alert('Test');
setTimeout(that.editObject, 1000);
}
}
new foo().editObject();
...
Whenever the Javascript engine will try to call "editObject()" defined in your jQuery function, it is out of your jQuery function's scope, it is actually in the global scope, but your editObject() function is defined in your jQuery function.
You can create the editObject in the global scope or create a reference to your jQuery function and pass it in your setTimeout call, like:
var that = this;
that.editObject = function() {
alert('Test');
setTimeout(that.editObject(), 1000);
}