js:快速点击两个按钮,出现两个接口数据在同一个按钮下面同时显示的bug

问:

if($(this).attr('tit') === 'undefined'){

reloadNotificationMessageList(0)

} else if($(this).attr('tit') === 'readed'){

reloadNotificationMessageList(1)

}这段代码有个问题,当我快速点击0和1进行切换的时候,由于已读信息太多接口返回时间过长,未读信息很少立刻就返回了,导致我快速来回切换后,虽然现在在未读信息列表,虽然现在没有未读信息,但是却同时显示了已读信息

回答:

javascript 复制代码
你描述的问题是由于异步请求的延迟导致的。当你快速切换未读和已读消息列表时,请求的返回顺序可能会混乱,导致界面显示不正确的数据。

为了解决这个问题,你可以使用一个标志变量来跟踪当前请求的状态,并确保只有最新的请求结果会更新界面。以下是一个改进的示例代码:

let currentRequestType = null;
let currentRequestId = 0;

function reloadNotificationMessageList(type) {
    currentRequestId++;
    currentRequestType = type;
    const requestId = currentRequestId;

    // 模拟 AJAX 请求
    setTimeout(function() {
        if (requestId === currentRequestId) {
            if (type === 0) {
                // 处理未读消息
                console.log('显示未读消息');
            } else if (type === 1) {
                // 处理已读消息
                console.log('显示已读消息');
            }
        }
    }, Math.random() * 2000); // 随机延迟模拟网络请求
}

$(document).ready(function() {
    $('.notification-tab').on('click', function() {
        const tit = $(this).attr('tit');
        if (tit === 'undefined') {
            reloadNotificationMessageList(0);
        } else if (tit === 'readed') {
            reloadNotificationMessageList(1);
        }
    });
});

在这个示例中,我们引入了两个变量 `currentRequestType` 和 `currentRequestId`。每次调用 `reloadNotificationMessageList` 时,我们增加 `currentRequestId`,并将当前请求的类型存储在 `currentRequestType` 中。在请求完成时,我们检查请求的 ID 是否与当前请求的 ID 匹配,如果匹配,则更新界面。

这样可以确保只有最新的请求结果会更新界面,避免了快速切换时界面显示不正确的数据。

你可以根据实际情况调整代码,例如将模拟的 `setTimeout` 替换为实际的 AJAX 请求。
相关推荐
phantom_1113 天前
Cursor 分析 bug 记录
bug·cursor
Direction_Wind4 天前
Flinksql bug: Heartbeat of TaskManager with id container_XXX timed out.
大数据·flink·bug
AIBigModel6 天前
智能情趣设备、爆 bug:可被远程操控。。。
网络·安全·bug
Direction_Wind7 天前
flinksql bug: Received resultset tuples, but no field str
bug
远瞻。7 天前
【bug】diff-gaussian-rasterization Windows下编译 bug 解决
windows·bug
中草药z7 天前
【测试】Bug+设计测试用例
功能测试·测试工具·测试用例·bug·压力测试·测试
我又来搬代码了7 天前
【Android】【bug】Json解析错误Expected BEGIN_OBJECT but was STRING...
android·json·bug
葵野寺8 天前
【软件测试】BUG篇 — 详解
bug·测试
青青子衿越10 天前
微信小程序右上角分享页面找不到路径bug
微信小程序·小程序·bug
刘火锅10 天前
Bug 记录:SecureRandom.getInstanceStrong()导致验证码获取阻塞
spring boot·spring·spring cloud·bug