Sirion
Sirion

Reputation: 927

Refer to outer function in Javascript (using jQuery)

I have these lines of javascript code which run when the page is loaded:

(function my_function() {
    //my stuff
})();

$("select#myselect").change( function() {
    if ($('select#myselect').val() == '1') {
        timer = setTimeout(my_function, 1000*5); //this line throws the error
    } else {
        if(typeof timer !== 'undefined'){
            clearTimeout(timer);
        }
    }
});

When the line highlighted is executed it throws: "Uncaught ReferenceError: my_function is not defined"

How can I fix it?

Upvotes: 1

Views: 128

Answers (3)

Michael Giovanni Pumo
Michael Giovanni Pumo

Reputation: 14774

You have what's called a closure going on, whereby you cannot access it (by design). Try this instead (also with some additional improvements...

function my_function() {
    //my stuff
}

// Call your function...
my_function();

var $mySelect = $("select#myselect");

$mySelect.on("change", function() {
    if ($mySelect.val() == '1') {
        timer = setTimeout(my_function, 1000*5); //this line throws the error
    } else {
        if(typeof timer !== 'undefined'){
            clearTimeout(timer);
        }
    }
});

I also cached your look up of select#myselect into a variable...because it will improve performance (admittedly marginally). In addition, I used the more preferred and newer on() method for your change event.

Hope this helps!

Upvotes: 0

Biduleohm
Biduleohm

Reputation: 752

Try to change this:

(function my_function() {
    //my stuff
})();

To this:

function my_function() {
    //my stuff
}
my_function();

Edit: Your function my_function isn't callable in the global scope because this pattern creates a local scope. Read this excellent wiki article for more informations.

Upvotes: 1

Levi Beckman
Levi Beckman

Reputation: 533

It looks like you are trying to run my_function first, and then run it again with the timer.

function my_function() {
    //my stuff
}
my_function();

$("select#myselect").change( function() {
    if ($('select#myselect').val() == '1') {
        timer = setTimeout(my_function, 1000*5); //this line throws the error
    } else {
        if(typeof timer !== 'undefined'){
            clearTimeout(timer);
        }
    }
});

Upvotes: 1

Related Questions