i am calling a jQuery plugin every 5 seconds with the following code
var now = new Date();
setInterval('$("#id").myplugin(now)', 1000);
The Plugin looks like this so far:
(function( $ ){
$.fn.myplugin = function(now) {
return this.each(function() {
alert(now.getTime());
});
}
})( jQuery );
However I get the error:
Uncaught ReferenceError: now is not defined
plugins.js:30 Uncaught TypeError: Cannot call method ‘getTime’ of undefined
So it looks as if the now time object doenst get passed to the plugin function and is not even defined in the setInterval method. I could probably call var now = new Date(); every time in the plugin function … but I want to know, why it doenst work like that and how to make it work ;). thx alot.
Use a function like this:
This way, the so-called scope of
nowis set to the function in which you callsetInterval. Otherwise, it is just the global object (window) you’re referring to, which doesn’t have anow.Secondly, passing a string works like
eval(), which is unsafe and slow: Why is eval unsafe in javascript?.