4

I have this code:

$(document).ready(function(){
    var callPage = function(){
        $.post('/pageToCall.php');
    };

    setInterval('callPage()', 60000);
});

and it gives me the error ReferenceError: Can't find variable: callPage. Why?

2
  • what you expect in callpage. function returns nothing it looks! Commented Aug 22, 2011 at 19:27
  • 1
    @zod: the return value of callPage (or lack thereof) is irrelevant. What's relevant is probably the type of the first parameter of setInterval, as Bryan suggested. Commented Aug 22, 2011 at 19:29

3 Answers 3

9

Try setInterval(callPage, 60000);.

If you pass a string to setInterval, then this string is evaluated in global scope. The problem is that callPage is local to the ready callback, it is not global.

There is hardly ever a reason to pass a string to setInterval (setTimeout). Always pass a function (to avoid exactly this kind of errors).

Sign up to request clarification or add additional context in comments.

4 Comments

yea... you're passing a reference to a function. Not a String.
@Felix Kling I refuse to gain reputation points from your answer, actually I would like to vote for your explanation :)
@Darhazer: Well, I hope you at least don't loose any through that... It was totally fine for me, I already have enough reputation points ;) Your answer was correct and I didn't see a need to provide my own just to explain it... anyway what's done is done.
@Felix Kling I've already earned the maximum daily reputation, so I'm not loosing anything either. But the purpose of SO is to educate readers, and not just giving a working code, so thank you for adding the explanation.
2

I suspect it's because callPage is a variable scoped to the anonymous function you're creating in the document.ready event. If you move the callPage definition outside that, does it work?

Comments

1
function callPage()
{
    $.post('/pageToCall.php');
};

$(document).ready(function()
{
    setInterval('callPage()', 60000);
});

It happens because callPage's scope is the anonymous function

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.