JavaScript页面刷新函数执行控制:单次执行及首次/每次区分执行
Hey there! Let's tackle your two questions one by one, since they both revolve around controlling function execution across page refreshes. We'll use browser storage (like localStorage) here because it retains data even when the page reloads—perfect for tracking execution state.
First, let's clarify two common interpretations of this question:
情况A:每次刷新页面,函数执行一次(页面生命周期内仅一次)
If you just need the function to run once per page load/refresh (and not repeat during the same page session), the simplest approach is to call it when the page finishes loading. Since every refresh starts a new page lifecycle, this guarantees one execution per refresh:
function myOneTimePerRefreshFunc() { console.log("This runs exactly once every time the page refreshes!"); } // Run when the page is fully loaded window.addEventListener('load', myOneTimePerRefreshFunc);
情况B:函数仅执行一次 across all refreshes(整个浏览器会话或永久)
If you want the function to run only once ever (even if the user refreshes multiple times), use localStorage to store a "has executed" flag:
function myOneTimeEverFunc() { const hasExecuted = localStorage.getItem('funcExecuted'); if (!hasExecuted) { console.log("This runs once and never again until storage is cleared!"); localStorage.setItem('funcExecuted', 'true'); } } window.addEventListener('load', myOneTimeEverFunc);
to_Execute_Once,每次刷新时执行to_Execute_Every_Time Based on your sample code (with the 7-second auto-refresh), here's how to make this work. We'll use localStorage to track whether we've already run the one-time function:
Full Working Code
// Check if we've already run the one-time function const hasRunInitial = localStorage.getItem('hasRunInitial'); function to_Execute_Once() { console.log("This runs ONLY on the first page refresh/load!"); } function to_Execute_Every_Time() { console.log("This runs EVERY time the page refreshes!"); } function my_Timer() { location.reload(); } // Handle execution when the page loads window.addEventListener('load', () => { // Run this function EVERY time the page refreshes (including the first) to_Execute_Every_Time(); // Run the one-time function ONLY if this is the first load/refresh if (!hasRunInitial) { to_Execute_Once(); localStorage.setItem('hasRunInitial', 'true'); } // Start the auto-refresh timer const my_Var = setInterval(my_Timer, 7000); });
Key Notes:
- If you want the one-time function to reset when the user closes the browser, replace
localStoragewithsessionStorage—it only persists for the current browser session. - To reset the one-time execution manually (for testing), run
localStorage.removeItem('hasRunInitial')in your browser's dev tools console. - Wrapping everything in the
loadevent ensures we don't run code before the page is fully ready.
内容的提问来源于stack exchange,提问作者Mahender Chowdary

