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 请求。
相关推荐
@Aurora.1 天前
【测试】BUG
bug
%d%d24 天前
undefined reference to CPUAllocatorSingleton::instance
bug
gxn_mmf5 天前
典籍知识问答重新生成和消息修改Bug修改
前端·bug
千里马学框架6 天前
重学安卓14/15自由窗口freeform企业实战bug-学员作业
android·framework·bug·systrace·安卓framework开发·安卓窗口系统·自由窗口
Bear on Toilet7 天前
Bug日记——实现“日期类”
开发语言·c++·bug
Direction_Wind7 天前
flinksql bug : Max aggregate function does not support type: CHAR
bug
mg6687 天前
Python Bug 修复案例分析:多线程数据竞争引发的bug 两种修复方法
bug
黎猫大侠8 天前
一次Android Fragment内存泄露的bug解决记录|Fragment not attach to an Activity
android·bug
七七小报8 天前
uniapp-商城-48-后台 分类数据添加修改弹窗bug
uni-app·bug
windwind20009 天前
发行基础:本地化BUG导致审核失败
游戏·青少年编程·编辑器·bug·创业创新·玩游戏