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

为何连续执行两次window.location.href仅最后一次生效?

Why Only the Last window.location.href Navigation Takes Effect?

Great question — this behavior trips up a lot of folks when they first start working with browser navigation in JavaScript. Let’s break down exactly what’s going on here:

1. Browser Navigation Prioritizes the Latest Request

When you set window.location.href, you’re telling the browser to initiate a navigation to a new URL. But browsers are designed to handle one navigation at a time for a given page context. If you fire off multiple window.location.href assignments in quick succession (like in the same sync code block), the browser will cancel any pending navigation requests and only act on the final one.

Think of it like giving the browser two conflicting directions back-to-back: it’s going to ignore the first one and follow the most recent instruction.

2. JavaScript’s Single-Threaded Execution Flow

JavaScript runs in a single thread, so your consecutive window.location.href lines execute synchronously one after another. The browser doesn’t start the navigation process immediately after the first assignment — it waits until the current chunk of sync code finishes running. By the time it’s ready to process the navigation request, it sees the last URL you set and uses that instead of the earlier ones.

For example, if you run this code:

window.location.href = "https://www.youtube.com";
console.log("First href set");
window.location.href = "https://www.google.com";
console.log("Second href set");

You’ll see both console logs appear in your dev tools, then the browser navigates to Google. The first navigation request gets completely overridden before it ever has a chance to load.

3. It’s a User Experience & Stability Guardrail

This behavior isn’t a bug — it’s a deliberate design choice. Imagine if every window.location.href assignment forced a navigation: users would get slammed with multiple consecutive page loads, which is disorienting and terrible for performance. Browsers prioritize a smooth, predictable experience, so they collapse duplicate or conflicting navigation requests into a single action.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:26:45