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

如何使JavaScript函数执行一次后替换XXP.run.pause()为XXP.run.play()?

Solution: Toggle 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 isFirstRun lives—this variable can't be accessed or modified from outside the doSkip function, keeping your state safe and isolated.
  • On the first call to doSkip, we execute XXP.run.play() and flip the isFirstRun flag to false.
  • Every subsequent call will hit the else block and use XXP.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:50:56