You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何终止浏览器中JavaScript无限循环?年龄校验程序循环异常排查

解决JavaScript无限循环问题及代码修复

一、终止浏览器中的无限循环

  • 打开浏览器开发者工具(快捷键:Chrome/Firefox按F12或Ctrl+Shift+I,Edge按F12)
  • 切换到「Sources」(Chrome)或「调试器」(Firefox)面板,点击暂停按钮(⏸️)即可中断脚本执行
  • 紧急情况下直接关闭当前标签页也能终止循环

二、代码问题分析与修复

你的循环无法终止的核心原因是:循环内部没有更新runagain变量的值。一旦runagain被设为true,循环条件永远为真,陷入无限循环。

修复后的完整代码

//→ Write a program using prompt function to take input of age as a value from the user and use alert to tell him if he can drive
let age = prompt("Please enter your age:");
age = parseInt(age); // Convert the input to a number

function check(age) {
  // 简化条件,同时修正拼写错误
  if (age >= 0 && age <= 90 && age >= 16) {
    alert("You can drive!");
  } else {
    alert("Sorry, you cannot drive or the number is not valid");
  }
}

check(age);
let runagain = confirm("Do you want to continue?");

while (runagain === true) {
  let b = prompt("Enter the age");
  b = parseInt(b);
  check(b);
  // 关键:在循环内部重新询问是否继续,更新runagain的值
  runagain = confirm("Do you want to continue?");
}

关键修改点

  • 在while循环末尾添加runagain = confirm("Do you want to continue?");,每次循环结束后重新确认用户意愿,以此更新循环条件
  • 修正提示文本拼写错误:canot→cannot,vaild→valid
  • 调整check函数的条件顺序,先判断年龄范围合法性,再判断是否达到驾驶年龄,逻辑更清晰

内容的提问来源于stack exchange,提问作者Sudip Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 03:25:59