views:

228

answers:

3

Hi all,

I have this code

window.onload = function() {            
    function foo() {
        alert("test");
    }
    setInterval("foo()",500)
}

Which returns undefined...When i use it outside the window.onload it works. Can anyone explain me why?

A: 

Try this:

function foo() {
    alert("test");
}

window.onload = function() {            
    setInterval("foo()",500)
}

It works for me.

Sarfraz
+6  A: 

Using a string command in setInterval() will try to look for the function in the global (window) namespace, but since the function is defined in a scope, it won't be found. You should pass the function itself to setInterval() instead.

window.onload = function() {            
    function foo() {
        alert("test");
    }
    setInterval(foo, 500);
}
Max Shawabkeh
A: 

Alternatively, you can define the function within the call to setInterval:

window.onload = function() {
    setInterval(
        function foo() {
            alert("test");
        },
        500
    );
}
Aaron