JavaScript — Accessing functions defined in jQuery scope / ReferenceError setInterval

To trigger a function defined in your document.ready function, you need to define a variable before the $(document).ready() that references the new function.

For example, function test() defined inside $(document).ready() is not accessible with setInterval('test()', 500), or something like onclick="javascript:test()"

$(document).ready( function() {
function test() { alert('test'); }
setInterval("test()", 500);
});

Will fail with ReferenceError

The following will work though:

var test;
$(document).ready( function() {
test = function() { alert('test'); };
setInterval("test()", 500);
});

Will work.

2 Comments

  1. Ian says:

    Thanks, you just saved me a lot of pain 🙂

  2. Johnd24 says:

    Woah! I’m really loving the templatetheme of this website. It’s simple, yet effective. A lot of times it’s hard to get that perfect balance between usability and visual appeal. I must say you have done a great job with this. In addition, the blog loads super quick for me on Firefox. Excellent Blog! dfacgdebdkga

Leave a Comment