Javascript 延迟一段时间后如何在window.onload中加载javascript函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5594176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:58:09  来源:igfitidea点击:

How to load javascript function in window.onload after some delay

javascriptfirefoxgoogle-chromefirefox3.6

提问by Achaius

I have couple of functions that should be triggered after some delay in onload event. It works fine in chrome but not in Firefox.

我有几个函数应该在 onload 事件延迟后触发。它在 chrome 中运行良好,但在 Firefox 中不起作用。

function foo() {
    // javascript code
}

window.onload = setTimeout(foo, delay);

function bar() {
    // javascript code
}

window.onload = setTimeout(bar, delay);

If I remove the delay, 'bar' gets invoked in Firefox and 'foo' and 'bar' get invoked in chrome. What could be the issue here?

如果我删除延迟,'bar' 会在 Firefox 中被调用,而 'foo' 和 'bar' 会在 chrome 中被调用。这里可能是什么问题?

回答by aroth

I'm surprised both functions get invoked in any browser. But you might have better luck with something like:

我很惊讶这两个函数在任何浏览器中都被调用。但是,您可能会在以下方面获得更好的运气:

function foo() {
    // javascript code
    setTimeout(bar, additionalDelay);
}

function bar() {
    // javascript code
}

window.onload = function() { setTimeout(foo, delay); };

Edit: Nevermind, I see why both of the timeouts execute. When you do something like:

编辑:没关系,我明白为什么两个超时都会执行。当您执行以下操作时:

window.onload = setTimeout(bar, delay);

window.onload = setTimeout(bar, delay);

...you are not actually setting window.onloadto execute your function after a delay. Instead this is immediately invoking setTimeout()to schedule your function call, and assigning the result (a handle to the scheduled function invocation) to window.onload. This is not correct, and will probably cause a runtime error in some browsers when they try to invoke window.onloadas a function.

...您实际上并未设置window.onload在延迟后执行您的功能。相反,这是立即调用setTimeout()以安排您的函数调用,并将结果(已安排的函数调用的句柄)分配给window.onload. 这是不正确的,并且可能会在某些浏览器尝试window.onload作为函数调用时导致运行时错误。

What you want to do instead is assign a function to window.onload, like:

您要做的是为 分配一个函数window.onload,例如:

window.onload = function() { 
    setTimeout(foo, delay); 
    setTimeout(bar, delay);
};

回答by Karol

You could use jQuery with sth like that:

你可以像这样使用jQuery:

$(document).ready(function() { /* your code */ });

or

或者

$(window).load(function() { /* your code */ });

jQuery automatically adds functions to stack, and run them all once event is triggered.

jQuery 自动将函数添加到堆栈,并在事件触发后运行它们。

If you want do it with only JS, you can make array of functions to trigger:

如果你只想用 JS 来做,你可以制作一组函数来触发:

function a() {
        alert('a');
    }

    function b() {
        alert('b');
    }

    var arr = new Array(a, b);

    window.onload = function() {
        for(var i = 0; i < arr.length; i++) {
            setTimeout(arr[i], 1000);
        }
    }

Hope it helps.

希望能帮助到你。

回答by álvaro González

I can see two base errors in your code. First of all, if you want to pass a function as argument you need to write the function name without parenthesis; if you add the parenthesis the function will be executedright then. See an example:

我可以在您的代码中看到两个基本错误。首先,如果要将函数作为参数传递,则需要编写不带括号的函数名;如果添加括号,则该函数将立即执行。看一个例子:

function foo(){
    alert("I am foo");
}
function bar(){
    alert("I am bar");
}

setTimeout(foo, 5000);
setTimeout(bar(), 10000);

Secondly, if you assign a value to the .onloadattribute with the =operator you'll overwrite its previous value, just like a = 3overwrites previous the value of a.

其次,如果您.onload使用=运算符为属性赋值,您将覆盖其先前的值,就像a = 3覆盖先前的 值一样a

function foo(){
    alert("I am foo");
}
function bar(){
    alert("I am bar");
}
window.onload = foo;
window.onload = bar;

From what I grasp, your main problem is to be able to addrather than replaceevent handlers. As usual, there isn't a universal API you can safely use in all browsers. If you are using a framework or library, it probably provides a cross-browser mechanism. Otherwise, you need to find or write your own. In the past, I've used this in several projects:

据我所知,您的主要问题是能够添加而不是替换事件处理程序。像往常一样,没有一个可以在所有浏览器中安全使用的通用 API。如果您使用的是框架或库,它可能会提供跨浏览器机制。否则,您需要自己查找或编写。过去,我在几个项目中使用过它:

... although it's not been updated since 2005 so I'd make sure it works properly in recent browsers.

...虽然它自 2005 年以来没有更新,所以我会确保它在最近的浏览器中正常工作。

回答by KooiInc

Try wrapping the timeout in a function:

尝试将超时包装在一个函数中:

window.onload = function(delay) {
                  setTimeout(foo, delay); 
                  setTimeout(bar, delay); 
                };