ajax超时不执行回调方案

ajax超时不执行回调方案

前言

​ 前两天有小伙伴找我说:面试官给了一个题,向服务器发出ajax请求,若1s内没有响应,则不执行回调,且只允许使用setTimeout。这些需求如何实现?

方案

​ 首先,要读懂这道题的核心。设置回调超时,且只允许使用setTimeout那么就是,不允许在主线程阻塞。那么这道题考的知识点显而易见是Event Loop事件循环了。如果想阻止回调,其实是不太可能了,因为ajax发出后,钩子函数就会被推入回调执行栈中。那么,我们只能通过修改回调方法来阻止执行了。

​ 首先,我们要启动一个服务器。我是用node.js来启动的。在本地启动还需要保证能被跨域,所以我们也要解决跨域。

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()

完事,整体思路就是这样的。

声明

脑瘫码农 纯属自学 如果错误 望请指正 共同学习 不胜感激

发布了31 篇原创文章 · 获赞 38 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/yhy1315/article/details/102523718