• Stars
    star
    162
  • Rank 232,284 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⚒️ Cooperative expensive tasks at 60fps via ES6 generators

Sinergia

npm travis

sinergia is a tiny (1KB gzipped) library to run cooperative expensive tasks without blocking the UI during the computations and keeping 60fps frame rate.

Demo

A live example is available at https://jiayihu.github.io/sinergia/, with an animated box which should remain smooth at 60fps.

There are 2 examples:

  1. Long running loop: Running an expensive function (with a 2mln iterations loop) with each item of an iterable

  2. Long merge sort: Running a common merge sort with an array of 100k items

It's possible to play with the demo locally cloning the repo and running:

cd demo # Go to demo folder
npm install # Or `yarn install`
npm start

Installation

npm install sinergia --save

Usage

The following examples use co to consume the generator functions.

In this example work runs a long loop for every item, but every 100000 iterations it interrupts and gives the control to sinergia, which will resume the execution of work when more suitable.

Execution tasks are by definition cooperative because they decide when to yield the control of the execution.

By using yield inside your work you can decide the priority of the execution. Yielding often will run the task smoothly chunk by chunk but it will complete in more time. On the other hand yielding fewer times it will complete the task sooner but it will block more the main thread. Yielding zero times is equal to running the task synchronously.

import co from 'co';
import { sinergia } from 'sinergia';

function* work() {
  const iterable = 'Absent gods.'.split('');
  let result = '';

  for (let item of iterable) {
    let x = 0;

    while (x < 2000000) {
      x = x + 1;

      // Tell sinergia when the task can be interrupted and resumed later
      if (x % 100000 === 0) yield result;
    }

    result += item; // Simple result of task
    console.log(`Result of iteration:`, result);
  }

  yield result; // Yield latest result
}

const execute = co(function* () {
  return yield* sinergia(work);
});
execute.then((result) => {
  // If the work wasn't interrupted
  if (result) console.log(`Result: ${result.value}`);
});

Abort execution

Since sinergia is just a generator, you can use the returned object to abort the execution using .return() method of generators.

The method will return { value: any } with the value of the result computed on the latest item before aborting.

import co from 'co';
import { sinergia } from 'sinergia';

function* work() {
  const iterable = 'Absent gods.'.split('');
  let result = '';

  for (let item of iterable) {
    let x = 0;

    while (x < 2000000) {
      x = x + 1;

      // Tell sinergia when the task can be interrupted and resumed later
      if (x % 100000 === 0) yield result;
    }

    result += item; // Simple result of task
    console.log(`Result of iteration:`, result);
  }

  yield result; // Yield latest result
}

let iterator;

const execute = co(function* () {
  iterator = sinergia(work);
  return yield* iterator;
});
execute.then((result) => {
  // If the work wasn't interrupted
  if (result) console.log(`Result: ${result.value}`);
});

window.setTimeout(() => {
  const result = iterator.return();
  console.log('Interrupted result', result.value);
}, 5000);

API

sinergia(work: GeneratorFunction): Generator

It runs asynchronously the work function in not blocking way. Returns the Generator object.

Browser support

sinergia requires polyfills for:

  1. Promise like es6-promise or core-js Promise. If you use babel-polyfill it's already included.

  2. requestAnimationFrame/cancelAnimationFrame. See this gist as example.

Credits

Ispiration comes largely from @LucaColonnello and @cef62.

More Repositories

1

pretty-algorithms

🌊 Pretty, common and useful algorithms with modern JS and beautiful tests
TypeScript
2,187
star
2

ng-animate

🌙 A collection of cool, reusable and flexible animations for Angular 14+
TypeScript
721
star
3

react-tiny-dom

🍙 A minimal implementation of react-dom using react-reconciler
JavaScript
465
star
4

react-kanban

🗓 Kanban board built with React.js and Redux
JavaScript
115
star
5

rx-polling

📬 RxJS-based polling library with exponential backoff
TypeScript
66
star
6

gmail-smart-compose

A study implementation of Gmail Smart Compose trained with Keras and used in browser with Tensorflow.js
Jupyter Notebook
27
star
7

talks

Collection of my public talks
JavaScript
11
star
8

wealth

Personal financial management app in pure Javascript
JavaScript
9
star
9

billy

📠 Angular 2+, RxJS and Redux Invoice Application
TypeScript
9
star
10

fedra-thesis

Next-generation system for Computing Continuum via WebAssembly (WASM)
WebAssembly
7
star
11

ygo

🃏 YuGiOh! PWA built with Web Components and hyperHTML
CSS
6
star
12

lab

Personal experiments with technologies
TeX
4
star
13

blog

Chronicles of a young developer's journey
MDX
3
star
14

gulp-react-browserify

💥 Boilerplate for React.js development with Gulp and Browserify
JavaScript
3
star
15

gh-issues-for-comments

🐈 Automatically create Github issues to use as blog comments
JavaScript
3
star
16

inkmark

Progetto P2
C++
2
star
17

libromastro

A webapp to keep track of your stock operations
TypeScript
2
star
18

fsm-editor

Finite State Machine editor
TypeScript
2
star
19

metalsmith-gh-comments

Metalsmith plugin for Github issues as blog comments
JavaScript
2
star
20

daisyhub

The favourite hub for Animal Crossing turnip exchange
TypeScript
2
star
21

telegram-nope-bot

A Telegram bot which alerts about NOPE value on tickers
TypeScript
2
star
22

webpack-react-boilerplate

Essential Webpack Boilerplate for React.js development with readable and minimal configuration
JavaScript
1
star
23

continuum

TeX
1
star
24

network-color

An educational game for anyone interested in Computer Science
TypeScript
1
star
25

brokerapi-rs

V2.16 Open Service Broker API compliant brokers in Rust
Rust
1
star
26

chattina

An MVC Chat, built in pure Javascript.
JavaScript
1
star
27

pwa

CSS
1
star
28

currency

💰Currency Exchange in React, Redux & Redux-Saga
JavaScript
1
star
29

jiayihu.github.io

Personal Website
JavaScript
1
star