简体   繁体   English

将setInterval与$(document).ready一起使用

[英]Using setInterval with $(document).ready

Am trying to invoke a function after the loading of the html page. 我正在尝试在加载html页面之后调用一个函数。 Its working fine and I want the function to be invoked after every 3 seconds and hence inserted the setInterval() for it. 它的工作正常,我希望每3秒调用一次该函数,并为此插入setInterval()。 But the function is not at all getting called. 但是根本不调用该函数。 Is there any problem with the syntax of setInterval()..? setInterval()的语法是否有问题?

<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>

<script>
$(document).ready( setInterval(function(){f()},3000); );

function f()
{
xhttp=new XMLHttpRequest();
xhttp.open("GET","/anu/get.php",true);
xhttp.send();
xhttp.onreadystatechange = function(){

if(xhttp.readyState==4){
var Display = document.getElementById('new');
Display.innerHTML = xhttp.responseText;
}

}

}

</script>
</head>
<body>

<p id="new"> </p>

<body>

</html>

It should be: 它应该是:

$(document).ready(function () {
  setInterval(function(){f()},3000);
});

The problem here is that setInterval returns a number , and passing a number to $(document).ready(...) does nothing. 这里的问题是setInterval 返回一个数字 ,并将数字传递给$(document).ready(...)没有任何作用。 Instead, you need to pass $(document).ready(...) a function, such as a function that starts off the setInterval call. 相反,您需要传递$(document).ready(...)一个函数,例如从setInterval调用开始的函数。

The other problem is that you included a semicolon after the setInterval , but semicolons are only valid on statements (which you can think of as "things that stand on their own line"). 另一个问题是,在setInterval之后添加了分号,但分号仅对语句有效(您可以将其视为“站在自己的行上的东西”)。 You can only pass expressions to functions like setInterval , and expressions don't have semicolons, so your extra semicolon before the closing parenthesis is an error, because the JS engine sees a semicolon-terminated statement where it expects there to be a no-semicolon expression. 您只能将表达式传递给setInterval函数,并且表达式没有分号,因此在右括号前的多余分号是错误的,因为JS引擎看到了以分号结尾的语句,该语句期望没有分号表达。


Also, you can shorten this to just 另外,您可以将其缩短为

$(document).ready(function () {
  setInterval(f, 3000);
});

or even 甚至

$(function () {
  setInterval(f, 3000);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM