Skip to content

Instantly share code, notes, and snippets.

@evanrs
Last active March 9, 2017 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evanrs/05fda32de726ff00a972f75aa5934963 to your computer and use it in GitHub Desktop.
Save evanrs/05fda32de726ff00a972f75aa5934963 to your computer and use it in GitHub Desktop.
Debounce a state change, sustain for the duration by repeated calls.

Debounce a state change with a sustain.

This is debounce with true|false passed to the callback.

In this example the value of scrolling will be true during the scroll event and for 250ms after.

import sustain from 'sustain';
let scrolling = false;

sustainScrolling = sustain(250, (state) => scrolling = state)

addEventListener('scroll', sustainScrolling)

In this example the value of sustainScrolling.state will reflect whether scrolling is true or false

import { sustainState } from 'sustain';

sustainScrolling = sustain(250)

addEventListener('scroll', sustainScrolling)

The value of sustainState.state can be given by the callback

sustainState(250, (sustained, prevState) =>
  sustained ? { count: prevState.count + 1 } : { count: 0 ))
import sustain from './sustain'
import sustainState from './sustainState'
export sustain;
export sustainState;
export default sustain;
{
"name": "sustain",
"version": "1.0.0",
"description": "Sustain a state for a time",
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://gist.github.com/05fda32de726ff00a972f75aa5934963.git"
},
"keywords": ["debounce", "sustain state"],
"author": "Evan Schneider",
"license": "ISC",
"bugs": {
"url": "https://gist.github.com/05fda32de726ff00a972f75aa5934963"
},
"homepage": "https://gist.github.com/05fda32de726ff00a972f75aa5934963"
}
export default function sustain (duration, toggle) {
let timeout;
let cycle = () => {
cycle.sustain();
timeout = setTimeout(cycle.release, duration)
}
cycle.suspend = () => clearTimeout(timeout);
cycle.sustain = () => cycle.suspend() + toggle(true);
cycle.release = () => cycle.suspend() + toggle(false);
return cycle;
}
import sustain from './sustain';
export default function sustainState (duration, toggle = (s) => s) {
let cycle = sustain(duration, (state) => {
cycle.state = toggle(state, cycle.state);
});
return cycle;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment