JavaScript打字计时程序循环输出问题求助
解决打字计时程序重复提示的问题
问题描述
编写一款检测指定时长内打字数量的程序,JS基础薄弱。当前遇到的问题:成功计算输入字符数后,'You have exceeded the time'提示会循环显示,次数与输入字符数一致,控制台最终结果也重复输出,重复次数和输入次数绑定。
问题原因
每次触发keydown事件(每按一次键),都会调用setTimeout(lock_input, 3000),相当于每按一次键就创建一个3秒后执行lock_input的定时器。比如按了5次键,就会生成5个独立的定时器,3秒后每个定时器都会执行lock_input,进而多次调用input_result,导致提示和日志重复出现。
修复后的代码
HTML代码
修正了input的type(原textbox不是合法的input类型,改为标准text):
<input type="text" id="input_box"> <input type="submit" id="input_submit"> <p id="input_para"></p>
JavaScript代码
添加标记变量避免重复创建定时器,同时优化输入框锁定逻辑:
let no_of_words = ''; // 标记定时器是否已启动 let timerStarted = false; const input_box = document.getElementById('input_box'); const input_para = document.getElementById('input_para'); const input_submit = document.getElementById('input_submit'); function input_result() { const info = document.createElement('p'); info.textContent = 'You have exceeded the time'; info.style.color = 'red'; input_para.appendChild(info); no_of_words = boxer.length; console.log(`You successfully typed ${no_of_words} characters in 3 seconds`); } function lock_input() { // 禁用输入框比单纯隐藏更符合交互逻辑 input_box.disabled = true; // 移除keydown事件监听,防止后续无效触发 input_box.removeEventListener('keydown', handleKeydown); input_result(); } const boxer = []; // 单独提取事件处理函数,方便后续移除监听 function handleKeydown(event) { // 仅第一次按键时启动定时器 if (!timerStarted) { setTimeout(lock_input, 3000); timerStarted = true; } boxer.push(event.key); } input_box.addEventListener('keydown', handleKeydown);
关键修改说明
- 添加
timerStarted变量:确保定时器只在第一次按键时创建一次,彻底避免重复触发 - 修正input类型:HTML无
textbox类型,改为标准text类型保证兼容性 - 提取独立事件处理函数:方便在计时结束后移除监听,防止用户继续输入无效内容
- 优化输入锁定方式:用
disabled = true替代visibility: hidden,让用户能看到输入框但无法操作,交互更合理
内容的提问来源于stack exchange,提问作者Gospel367
相关产品推荐
相关产品推荐

