1

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?

1

3 Answers 3

1

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);
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

@Bergi, I made a comment without thinking about what I was saying. Removing
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.