Skip to content

guygubaby/mini-scheduler

Repository files navigation

Mini Scheduler

A mini scheduler for task handler in browser

Why scheduler

1. Concurrent

Concurrency behavior make your code run faster

2. Time Slicing

  1. before before-time-slicing

  2. after after-time-slicing

Install

yarn add mini-scheduler

Features

  1. time slicing (schedule long task not prevent render)
  2. concurrent (async pool support)

Usage

Time Slicing Mode (for better render performance)

  1. fast jobs

    import { ts, TimeSlicingConfig } from 'mini-scheduler';
    
    const arr = Array.from({ length: 20 }, (_, i) => i);
    
    const timeSlicingConfig: TimeSlicingConfig = {
      fps: 60,
      renderTime: 10,
      funcType: 'setTimeout',
    };
    
    const fastTask = () => {
      const start = performance.now();
      while (performance.now() < start + 5) {}
      console.log('long task done');
    };
    
    ts(arr, fastTask, timeSlicingConfig);
  2. slow jobs

    import { ts, TimeSlicingConfig } from 'mini-scheduler';
    
    const arr = Array.from({ length: 20 }, (_, i) => i);
    
    const timeSlicingConfig: TimeSlicingConfig = {
      fps: 60,
      renderTime: 10,
      funcType: 'setTimeout',
    };
    
    function* longTaskGenerator() {
      const start = performance.now();
      while (performance.now() < start + 50) {
        yield;
      }
      console.log('long task done');
    }
    
    ts(arr, longTaskGenerator, timeSlicingConfig);
  3. slow job

    import { tsGenerator, TimeSlicingConfig } from 'mini-scheduler';
    
    const timeSlicingConfig: TimeSlicingConfig = {
      fps: 60,
      renderTime: 10,
      funcType: 'setTimeout',
    };
    
    function* veryLongTaskGenerator() {
      const start = performance.now();
      while (performance.now() < start + 500) {
        yield;
      }
      console.log('very long task done');
    }
    
    tsGenerator(veryLongTaskGenerator(), timeSlicingConfig);

Concurrent Mode (for better task runner performance)

import { asyncPool } from 'mini-scheduler';

const arr = Array.from({ length: 20 }, (_, i) => i);

const task = <T>(item: T) => {
  return new Promise((resolve) => {
    window.setTimeout(async () => {
      console.log(item, 'done');
      resolve(item);
    }, 2000);
  });
};

asyncPool(2, arr, async (item, _) => {
  await task(item);
});

References