Skip to main content

Web worker

点击展开代码
Result
Loading...
Live Editor
function CounterWithWorker() {
  const [count, setCount] = React.useState(0);
  const workerRef = React.useRef(null);

  React.useEffect(() => {
    // 创建内联 Worker
    const workerCode = `
      self.onmessage = function(e) {
        if (e.data === 'increment') {
          let result = 0;
          // 模拟耗时计算
          for (let i = 0; i < 100000000; i++) {
            result += Math.random();
          }
          postMessage('done');
        }
      }
    `;
    
    const blob = new Blob([workerCode], { type: 'application/javascript' });
    const worker = new Worker(URL.createObjectURL(blob));
    workerRef.current = worker;

    worker.onmessage = (e) => {
      if (e.data === 'done') {
        setCount(c => c + 1);
      }
    };

    return () => {
      worker.terminate();
    };
  }, []);

  const handleIncrement = () => {
    workerRef.current.postMessage('increment');
  };

  return (
    <div style={{ 
      padding: '1rem', 
      border: '1px solid #ddd', 
      borderRadius: 4,
      maxWidth: '400px'
    }}>
      <h3>Web Worker 计数器</h3>
      <p>当前计数: {count}</p>
      <div style={{ display: 'flex', gap: '8px' }}>
        <button 
          onClick={handleIncrement}
          style={{ padding: '8px 12px' }}
        >
          使用Worker增加
        </button>
        <button 
          onClick={() => setCount(0)}
          style={{ padding: '8px 12px' }}
        >
          重置
        </button>
      </div>
      <p style={{ fontSize: '0.8em', color: '#666', marginTop: '8px' }}>
        注意: Worker会模拟耗时计算,点击后会有短暂延迟
      </p>
    </div>
  );
}

render(<CounterWithWorker />);