function getXHR(){
var xhr=null;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
} else if (window.ActiveXObject){
try{
xhr=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("您的浏览器暂不支持Ajax");
}
}
}
return xhr;
}
//ajax与setTimeout排队问题
function ajax(url,method){
var xhr=getXHR();
xhr.onreadystatechange=function(){
console.log("xhr.readyState:"+this.readyState);
}
xhr.onloadstart=function(){
console.log("onloadStart");
}
xhr.onload = function(){
console.log("onload");
}
xhr.open(method,url,true);
xhr.setRequestHeader("Cache-Control",3600);
xhr.send();
}
var timer=setTimeout(function(){
console.log("setTimeout");
},0);
ajax("http://localhost:63342/project1/js3/html/Ajax%E5%AD%A6%E4%B9%A0.html?_ijt=i9plfqpg77fjialq6b8140t8d3","GET");
console.warn("这里的log并不是最先打印出来的");
为什么会是这么一种结果?哪位大神可以具体解释一下?

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
setTimeout 是异步的
即使设置setTimeout的延迟时间为 0,浏览器还是会给设置几毫秒甚至好几十毫秒的延迟,具体看操作系统
setTimeout会在下一次事件循环才执行
ajax是异步的, 但一次ajax 请求, 并非所有的部分都是异步的, "readyState==1"的 onreadystatechange 回调以及 onloadstart 回调就是同步执行的.
按我的理解,就是ajax函数自上而下执行,先执行send(),然后触发了onreadystatechange开始打印,onloadstart开始,send结束onload。而setTimeout这个函数,我记得有句对它的解释是待页面加载稳定后执行,虽然写0,也是最后的,而console那个是在ajax()之后,可能跟ajax的时间有关系,所以它打印的位置可能不固定,不知道理解的对不对