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

JavaScript实现每2秒切换URL功能运行异常问题求助

问题排查与解决方案

问题根源

  • 核心逻辑错误:调用location.replace()跳转后,当前页面的所有JS上下文、全局变量、定时器都会被完全销毁,你编写的切换逻辑代码不存在于新加载的外部站点中,自然不会执行后续的切换动作,也不会输出调试日志。
  • 结构错误:你的HTML代码不规范,<button>元素放在了<head>和<body>标签之外,部分浏览器可能无法正常渲染和绑定点击事件。

实现方案

要实现多页面定时切换效果,必须让控制脚本始终在顶层页面运行,不能直接替换顶层页面地址,改用<iframe>标签承载要切换的页面即可。

修正后可运行代码

<!DOCTYPE html>
<html>
<head>
    <script>
        let a = 2;
        let timer = null;
        console.log(a);

        function Start() {
          // 首次加载第一个页面到iframe
          document.getElementById("frame").src = "https://www.w3schools.com";
          // 全局仅初始化一次定时器,避免重复创建导致逻辑混乱
          if(!timer) {
            timer = setInterval(myFunction, 2000);
          }
        }
        
        function myFunction() {
            console.log(a);
            const frame = document.getElementById("frame");
            if (a == 1){
                frame.src = "https://www.youtube.com/";
                a=2;
            } else {
                frame.src = "https://www.google.com/";
                a=1;
            }
        }
    </script>
</head>
<body>
    <button onclick="Start()">Start script</button>
    <iframe id="frame" width="100%" height="90%" frameborder="0"></iframe>
</body>
</html>

注意事项

  • 部分站点设置了X-Frame-Options响应头禁止被iframe内嵌,遇到这类站点时无法正常加载,请改用允许内嵌的站点测试。

内容的提问来源于stack exchange,提问作者Piferrer Sagrera

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:15:02