如何使JavaScript函数执行一次后替换XXP.run.pause()为XXP.run.play()?
play()/pause() on First doSkip Trigger Got it, let's sort this out! The core issue here is tracking whether doSkip has been run for the first time, and a closure is exactly the right tool for this—it lets us keep that state private without cluttering the global scope.
Here's how to implement it properly:
Basic Standalone Function
If doSkip is a standalone function, wrap it in an Immediately Invoked Function Expression (IIFE) to create a private state variable:
const doSkip = (function() { // Private state variable to track first run let isFirstRun = true; return function() { XXP.run.removeListener('canper', XXP.Skip); XXP.run.currentTime = XXP.skipTo; // Check if this is the first execution if (isFirstRun) { XXP.run.play(); // Replace pause() with play() on first run isFirstRun = false; // Flip the flag so future runs use pause() } else { XXP.run.pause(); // Original behavior for subsequent runs } }; })();
If doSkip is an Object Method
If doSkip is part of an object (matching your original code's structure), adjust the closure to fit the object context:
// Example object containing the doSkip method const yourTargetObject = { doSkip: (function() { let isFirstRun = true; return function() { XXP.run.removeListener('canper', XXP.Skip); XXP.run.currentTime = XXP.skipTo; if (isFirstRun) { XXP.run.play(); isFirstRun = false; } else { XXP.run.pause(); } }; })() };
How This Works
- The IIFE creates a private scope where
isFirstRunlives—this variable can't be accessed or modified from outside thedoSkipfunction, keeping your state safe and isolated. - On the first call to
doSkip, we executeXXP.run.play()and flip theisFirstRunflag tofalse. - Every subsequent call will hit the
elseblock and useXXP.run.pause()as originally intended.
Your earlier closure attempt might have missed encapsulating the state variable within the closure's scope—this approach fixes that by locking the flag inside the IIFE's private context.
内容的提问来源于stack exchange,提问作者ghosted

