Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure/scope JavaScript/jQuery

I'm trying to group some exisiting top-level functions inside a closure (to avoid polluting the global namespace) but I'm not quite getting it to work.

First, all the JS works outside my anonymous function, but once I put it in the anonymous function I get an error of "crossfade is not defined". Does anyone see anything completely obvious that I am missing?

I'm not quite getting why the the setInterval/crossfade works outside the anonymous function but not inside. Anything inside start() should be able to see vars/functions outside start() and it should all be protected in the closure created by the top-level anonymous function? I'm not trying to access anything within crossfade(), I'm just trying to execute it.

(function($) {

    //vars up here that internal functions can access
    //also using some jquery inside here, so using $

    function crossfade() {
        //body here
    }

    //other functions

    function start() {
        //body here

         cInterval = setInterval('crossfade()', 5000);
    } 

})(jQuery);
like image 314
magenta placenta Avatar asked Nov 24 '09 18:11

magenta placenta


1 Answers

Using setInterval('crossfade()', 5000); doesn't create a closure - it creates a string to be eval()d. You should use a function instead:

setInterval(function() { crossfade(); }, 5000);
like image 166
Greg Avatar answered Oct 02 '22 02:10

Greg