npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

synchronous-timeout

v1.0.3

Published

`synchronous-timeout` allows developers to wrap arbitrary synchronous or asynchronous functions so that they can self-abort based on a signal from a worker thread. This is achieved by automatically injecting checks into the function code at the beginning

Downloads

261

Readme

synchronous-timeout

synchronous-timeout allows developers to wrap arbitrary synchronous or asynchronous functions so that they can self-abort based on a signal from a worker thread. This is achieved by automatically injecting checks into the function code at the beginning of all the function's block statements. When a shared memory byte is set by the worker thread, the running function detects this and aborts its execution.

Key Feature

  • Automatic Injection of Abort Checks: Wrap any function to automatically include checks that monitor a shared memory signal. If the signal indicates an abort (set by a worker thread), the function will self-terminate.

Installation

Install via npm:

npm install synchronous-timeout

Usage

injectAbortCheck(fn)

Wraps a function with abort-checking capability. The wrapped function will periodically check a shared memory byte to determine if it should self-abort, as signaled by a worker thread.

Parameters

  • fn (Function): The function you want to wrap. This can be any synchronous or asynchronous function.

Returns

  • A new function that behaves like the original but will self-abort if the shared memory signal is set.

Example

import { injectAbortCheck } from 'synchronous-timeout';

// Original function
function computePrimes(limit) {
  const primes = [];
  for (let num = 2; num <= limit; num++) {
    let isPrime = true;
    for (let factor = 2; factor <= Math.sqrt(num); factor++) {
      if (num % factor === 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) primes.push(num);
  }
  return primes;
}

// Wrap the function to enable aborting
const abortableComputePrimes = injectAbortCheck(computePrimes);

// Start the worker thread to signal an abort after a timeout
// Assume startAbortWorker is a function that starts the worker and sets the abort signal
import { startAbortWorker } from 'synchronous-timeout';

const worker = startAbortWorker(5000); // Abort after 5 seconds

// Use the wrapped function
try {
  const primes = abortableComputePrimes(1e7);
  console.log('Primes computed:', primes);
} catch (error) {
  console.error('Function aborted:', error.message);
} finally {
  worker.terminate();
}

In this example:

  • The computePrimes function is CPU-intensive and may run for a long time.
  • By wrapping it with injectAbortCheck, it will periodically check if it should abort.
  • A separate worker thread signals an abort by setting a shared memory byte after 5 seconds.
  • If the abort signal is set, the function will throw an error and terminate early.

How It Works

  • Code Transformation: injectAbortCheck converts the original function into a string and uses Babel to inject abort checks at the beginning of each code block (e.g., loops, functions).
  • Shared Memory Monitoring: The injected checks read a shared byte from a SharedArrayBuffer. If the byte indicates an abort signal, the function throws an error.
  • Worker Thread Signal: A separate worker thread can set the abort signal by modifying the shared memory byte. This allows for asynchronous control over the function's execution.

Example

For a function like this:

async function long_running_code(n) {
  let result = 0;
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      result += i + j;
      if (i % 10 === 0) {
        console.log(`Intermediate result at i=${i}, j=${j}: ${result}`);
      }
    }
  }
  return result;
}

Code is injected in every block statement, resulting in the following abort-enabled function:

async function long_running_code(n) {
  check_abort(); // Injected ABORT check
  let result = 0;

  for (let i = 0; i < n; i++) {
    check_abort(); // Injected ABORT check

    for (let j = 0; j < n; j++) {
      check_abort(); // Injected ABORT check
      result += i + j;

      if (i % 10 === 0) {
        check_abort(); // Injected ABORT check
        console.log(`Intermediate result at i=${i}, j=${j}: ${result}`);
      }
    }
  }

  return result;
}

SharedArrayBuffer Compatibility

synchronous-timeout relies on SharedArrayBuffer for communication between the main thread and the worker thread. Please note that SharedArrayBuffer availability depends on the environment and browser support. For more information on compatibility, refer to the MDN documentation on SharedArrayBuffer.

Ensure that your target environment supports SharedArrayBuffer and that any necessary cross-origin isolation policies are correctly configured.

Notes

  • The function wrapping is transparent; you use the wrapped function just like the original.
  • The abort mechanism is cooperative. The function checks the abort signal at block-level boundaries, so it won't abort during atomic operations.
  • This is particularly useful for long-running synchronous functions where you might need to enforce a timeout.

Limitations

  • Granularity of Checks: Abort checks are injected at the beginning of code blocks. Internal blocks that call other (non-abort-injected) functions will abort only at the block level that last supported the check.
  • Environment Requirements: Requires an environment that supports SharedArrayBuffer and worker threads (e.g., modern browsers with proper cross-origin isolation, Node.js with worker support).

License

ISC License