javascript-setInterval函数在页面加载时不会立即启动
我有这样的代码,可以在给定的时间间隔连续访问url:javascript-setInterval函数在页面加载时不会立即启动,javascript,html,json,Javascript,Html,Json,我有这样的代码,可以在给定的时间间隔连续访问url: window.setInterval(function(){ var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var valr5 = JSON.parse(this.response
window.setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var valr5 = JSON.parse(this.responseText);
document.getElementById("wind").innerHTML = valr5.wind;
}
};
xmlhttp.open("GET", "sample.com/", true);
xmlhttp.send();
}, 30000);}
我的问题是脚本将在30秒后运行,正如代码中设置的那样。因此,页面在30秒内是空白的
我要做的是在页面加载时,脚本将运行,这样我就不会看到空白页面,并且从中每隔30秒左右访问一次URL
我该怎么做?谢谢。先将函数保存在变量中,调用函数,然后使用它调用
setInterval
:
const updateWind = () => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var valr5 = JSON.parse(this.responseText);
document.getElementById("wind").innerHTML = valr5.wind;
}
};
xmlhttp.open("GET", "sample.com/", true);
xmlhttp.send();
};
updateWind();
window.setInterval(updateWind, 30000);
首先将函数保存在变量中,调用函数,然后使用它调用
setInterval
:
const updateWind = () => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var valr5 = JSON.parse(this.responseText);
document.getElementById("wind").innerHTML = valr5.wind;
}
};
xmlhttp.open("GET", "sample.com/", true);
xmlhttp.send();
};
updateWind();
window.setInterval(updateWind, 30000);