下面是我准备构建网站的代码片段。
<小时/><script type="text/javaScript">
function h(d) {
console.log("hello");
return;
};
function func(callback) {
var httpRequest; // create our XMLHttpRequest object
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Internet Explorer old versions
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() {
// inline function to check the status
if (httpRequest.readyState === 4 &&
httpRequest.status === 200) {
callback(httpRequest.responseText);
// call the callback function
}
};
httpRequest.open("GET", '/try_ajax',true);
httpRequest.send();
}
// call the function
setInterval(func(h), 10000); // Timer is triggered here
</script>
<小时/>
有趣的是,虽然我将间隔设置为 10 秒,但在我的控制台中“hello”仅出现一次。但 10 秒后它应该会继续出现。请帮忙!
最佳答案
这是错误的
setInterval(func(h), 10000); // Timer is triggered here
您的意思是获取从 func(h)
返回的任何内容并将其分配给超时
setInterval(function(){func(h);}, 10000); // Timer is triggered here
关于javascript - Javascript 异步函数调用中 setInterval 函数异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21335954/