Take the 2-minute tour ×

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() {
   })( 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.

share|improve this question

2 Answers 2

up vote 5 down vote accepted

Use a function like this:

var now = new Date();

setInterval(function() {
}, 1000);

This way, the so-called scope of now is set to the function in which you call setInterval. Otherwise, it is just the global object (window) you're referring to, which doesn't have a now.

Secondly, passing a string works like eval(), which is unsafe and slow: Why is eval unsafe in javascript?.

share|improve this answer
This is exactly the way to do it. NEVER pass setInterval a string - always pass it a function. –  Chris Baker Jun 1 '11 at 20:16
@Chris: Thanks, added your point. –  pimvdb Jun 1 '11 at 20:18

Use this instead:

setInterval(function(){$("#id").myplugin(now)}, 1000);
share|improve this answer

Your Answer


