ajax timeout callback is not executed program
Foreword
Two days ago I was looking for a small partner, he said: give the interviewer a question, issue ajax request to the server, if there is no response within 1s, the callback is not executed, and only allowed to use setTimeout
. How to achieve these requirements?
Program
First, we must understand the core of solving the problem. Set the timeout callback, and only allows the use of setTimeout
it is, do not allow blocking the main thread. This question is so obvious test of knowledge is Event Loop
the event of the cycle. If you want to stop callback, in fact, it is unlikely, because the ajax issue, hook callback function will be pushed into the execution stack. So, we can only modify the callback method to stop the execution.
First of all, we want to start a server. I used node.js
to start. Local start also need to ensure that can be cross-domain, so we have to solve cross-domain.
server.js
const http = require('http');
const server = http.createServer();
server.on('request', function (req, res) {
var now = Date.now();
while(Date.now()-now<3000){//延时3秒
}
res.setHeader('Access-Control-Allow-Origin', '*');//设置跨域
res.end("hello world");
})
server.listen(3000, "127.0.0.1", function () {
console.log('服务器启动成功啦!')
})
index.js
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
function ajax(){
var xhr = new XMLHttpRequest();
let timeOut = false;
xhr.open("get","http://127.0.0.1:3000",true);
xhr.send()
setTimeout(()=>{
timeOut = true;
},1000)//超过1s设置状态
xhr.onreadystatechange = ()=>{
if(xhr.readyState == 4){
if(xhr.status == 200){
if(timeOut){//根据状态调整回调方法
console.log("超时!")
}else{
console.log("未超时 执行")
}
}
}
}
}
ajax()
Bin, the whole idea is this.
statement
Agriculture is purely cerebral palsy code look wrong please correct me if self-learning together grateful