setInterval and [removed] problem

后端 未结 4 1734
醉梦人生
醉梦人生 2021-01-22 21:13

I have this code

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

相关标签:
4条回答
  • 2021-01-22 21:27

    Try this:

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

    It works for me.

    0 讨论(0)
  • 2021-01-22 21:39

    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 讨论(0)
  • 2021-01-22 21:49

    Using a string command 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);
    }
    
    0 讨论(0)
  • 2021-01-22 21:49

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

    window.onload = function() {
        setInterval(
            function foo() {
                alert("test");
            },
            500
        );
    }
    
    0 讨论(0)
提交回复
热议问题