如何延迟调用javascript函数? [英] How to delay calling of javascript function?

查看:122
本文介绍了如何延迟调用javascript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的新手。

I'm new to JavaScript.

我想在aspx页面加载页面后调用JavaScript / jQuery函数。

I would like to call JavaScript / jQuery function after the page load in aspx page.

我尝试使用< form onload =function()> window.load = function(){ } ,但在某些内容完全加载之前,JavaScript仍会触发。

I tried using <form onload="function()"> and window.load = function(){}, but the JavaScript is still trigger before some of the content fully loaded.

是否可以在aspx页面中的 Page_PreRender 期间调用,而不是在代码后面调用,这样我就可以延迟JavaScript函数?

Is it possible to call during Page_PreRender in aspx page and not in code behind, so that I can delay the JavaScript function ?

我尝试了 setTimeout(function(),5000)来解决问题。

然而 setTimeout()似乎与某些浏览器不兼容,例如:在Google Chrome中引起循环。

However setTimeout() seem like is not compatible with some browser, e.g: caused looping in Google Chrome.

推荐答案

setTimeout 自1996年以来与所有浏览器兼容。您应该避免评估functionName()而是:

setTimeout is compatible with all browsers since 1996. You should avoid the evaluation of "functionName()" and instead do:

setTimeout(functionName,5000)

UPDATE:如果您最初期望传递给函数的变量而在超时时没有传递,则需要执行此操作:

UPDATE: If you initially expect a variable passed to the function and none when in the timeout, you need to do this instead:

setTimeout(function() { functionName() },5000)

因为setTimeout会将超时ID传递给函数,如果它像i一样被调用在第一个例子中。

because setTimeout will pass the timeout ID to the function, if it is called like in the first example.

但是你错误地调用 onload ,所以你需要这样做:

However you are calling the onload incorrectly, so you need to do either this:

window.onload=function() {
  // your stuff
}

或者,因为你正在使用 jQuery ,这个:

or, since you are using jQuery, this:

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

或只是这样:

$(function() {
    // your stuff
});

这篇关于如何延迟调用javascript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆