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

基于索引控制活跃构造函数:启停及进程终止需求

Controlling Constructor Instances via Array Index (ID)

Got it, let's break down how you can control constructor instances using their array index (your "ID") — including starting and terminating individual processes. Here's a practical approach that works for most scenarios:

1. Build Constructor with Built-in Control Logic

First, design your constructor to include methods for starting/stopping its process, plus a flag to track its running state. This lets each instance manage its own lifecycle.

function WorkerProcess() {
  this.isRunning = false;
  this.processHandle = null; // Stores reference to the running process (interval, child process, etc.)

  // Start the process
  this.start = () => {
    if (this.isRunning) {
      console.log('Process is already running');
      return;
    }
    this.isRunning = true;
    console.log('Process started');

    // Example: Simulate a long-running task with setInterval
    this.processHandle = setInterval(() => {
      console.log(`Process ${processInstances.indexOf(this)} is active`);
    }, 1000);
  };

  // Stop the process
  this.stop = () => {
    if (!this.isRunning) {
      console.log('Process is already stopped');
      return;
    }
    this.isRunning = false;
    clearInterval(this.processHandle); // Clean up the running task
    console.log('Process stopped');
  };
}

2. Track Instances in an Array (Index = ID)

Store all your constructor instances in an array — the index of each item becomes its unique ID. This makes it trivial to look up and control specific instances.

// Initialize an array to hold all process instances
const processInstances = [];

// Create and add instances to the array
processInstances.push(new WorkerProcess()); // ID: 0
processInstances.push(new WorkerProcess()); // ID: 1
processInstances.push(new WorkerProcess()); // ID: 2

3. Control Instances Using Their Index

Now you can directly start/stop any instance by referencing its array index. You can even wrap this in a helper function to handle edge cases.

Basic Control

// Start the instance with ID 1
processInstances[1].start();

// Stop the instance with ID 1 after 5 seconds
setTimeout(() => {
  processInstances[1].stop();
}, 5000);

Helper Function for Safe Control

Add a helper to validate IDs and actions, preventing errors from invalid inputs:

function manageProcess(id, action) {
  // Check if ID is within valid range
  if (id < 0 || id >= processInstances.length) {
    console.error(`Error: Process ID ${id} doesn't exist`);
    return;
  }

  // Execute the requested action
  if (action === 'start') {
    processInstances[id].start();
  } else if (action === 'stop') {
    processInstances[id].stop();
  } else {
    console.error(`Error: Invalid action "${action}" — use "start" or "stop"`);
  }
}

// Use the helper
manageProcess(0, 'start'); // Starts ID 0
manageProcess(2, 'stop');  // Stops ID 2
manageProcess(5, 'start'); // Logs error (invalid ID)

4. Adjust for Complex Processes

If your constructor spawns external processes (like Node.js child_process or browser Web Workers), update the stop() method to use the appropriate termination logic:

  • For Node.js child processes: Replace clearInterval with this.processHandle.kill()
  • For Web Workers: Use this.processHandle.terminate()

The core pattern stays the same: track instances in an array, use their index as the ID, and call instance-specific control methods.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:31:01