按钮点击后CSS类无法即时更新问题求助
解决按钮CSS类更新后界面不及时刷新的问题
你的问题根源在于timer()函数里的同步死循环:JavaScript是单线程模型,while(true)会持续占用主线程,浏览器完全没有机会重绘DOM——哪怕你已经修改了按钮的className,界面也得等这个循环结束才能更新(但这个循环会卡死线程,几乎无法正常终止)。
解决方案:用异步定时替换同步循环
把阻塞主线程的while循环改成异步的定时检查,用setInterval实现,这样不会占用主线程,UI就能及时刷新。
修改后的代码如下:
1. 重写timer函数
function timer(time){ let Time = new Date(Date.parse(time)); const timeMin = Time.getMinutes(); console.log(Time); // 每100毫秒检查一次时间,避免阻塞主线程 const checkInterval = setInterval(() => { let currentTime = new Date(); currentTime = currentTime.getMinutes(); // 0.1分钟等于6秒,满足条件时执行后续逻辑 if((currentTime - timeMin) >= 0.1){ clearInterval(checkInterval); // 清除定时器 // 执行AJAX请求 fetch('/background_process_test') .then(response => response.json()) .then(text => { console.log('GET response:'); console.log(text.greeting); if(text.greeting == true){ console.log(text.greeting); // 此处可添加45分钟后重新检查房间状态的逻辑 } }); } }, 100); }
2. 调整color_check函数的调用逻辑
function color_check(color, id){ if(color == "btnRed"){ alert("Slot already booked!!!!"); }else if(color == "btnYellow"){ alert("You have already booked this slot!!!!!"); }else if(color == "btnGreen"){ alert("Slot booked!!!!!"); color = "btnYellow"; document.getElementById(id).className = color; // 直接启动定时器,无需接收返回值 timer(new Date()); console.log("1: 定时器已启动"); } return color; }
修改后,按钮点击时className会立即更新,浏览器能及时渲染样式变化,同时异步定时检查不会阻塞主线程,后续AJAX请求也能正常执行。
内容的提问来源于stack exchange,提问作者padi Foley
相关产品推荐
相关产品推荐

