最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - setInterval and window.onload problem - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Jan 29, 2010 at 13:44 chchristchchrist 19.8k11 gold badges49 silver badges83 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 13

Using a string mand in setInterval() will try to look for the function in the global (window) scope, but since the function is defined in a local 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);
}

Try this:

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

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

It works for me.

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

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

You should set the function to setInterval() instead.

Also remember clearing the interval on window.onunload or window.beforeonunload

const CheckFoo = () => {
    const start = new Date().getTime();

    console.log("check", start);
};
window.onload = function foo() {
    window.setInterval(CheckFoo, 500);
};

window.onunload = function foo() {
    window.clearInterval(CheckFoo);
};
发布评论

评论列表(0)

  1. 暂无评论