Skip to content

use embedded worker  #95

Open
Open
@zerozoo-a

Description

@zerozoo-a
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  embedded worker approach example
  <button>check if main thread is blocked</button>
<script type="text/javascript">
  const process = f => {
    const isOkWorker = Blob && URL && URL.createObjectURL;

    if(isOkWorker) {
      const blob = new Blob([`onmessage = ({data}) => postMessage((${f})(data));`], { type: 'text/javascript' });
      const url = URL.createObjectURL(blob);
      const worker = new Worker(url);

      const onMessage = (res) => worker.onmessage = ({data}) => res(data);
      const onError = (rej) => worker.onerror = ({data}) => rej(data);

      return data => new Promise((res, rej) => {
        onMessage(res);
        onError(rej);
        worker.postMessage(data)
      })
    } else {
      return data => f(data);
    }
  }

  const w = process(a => a + 1);
  const k = w(100).then(res => console.log('res >>>',res));
  console.log("🚀 ~ file: index.html:33 ~ k:", k);


  /** cpu intensive function block main thread 1 sec */
  function blockCpuFor1Sec(sec = 1) {
  const startTime = Date.now();

  // A simple, CPU-intensive, inefficient Fibonacci function
  function calculateFibonacci(n) {
    if (n < 2) {
      return n;
    }
    return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);
  }

  // Find the highest Fibonacci number it can calculate within 1 second
  let n = 0;
  while (Date.now() - startTime < sec * 1000) {
    calculateFibonacci(n);
    n++;
  }

  console.log(`Calculated Fibonacci(${n}) in 1 second`);
}

blockCpuFor1Sec(1)



</script>
</body>
</html>

참조:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
https://www.bsidesoft.com/8167

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions