How to use throttle-debounce - 10 common examples

To help you get started, we’ve selected a few throttle-debounce examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cockpit-project / cockpit / pkg / networkmanager / firewall-client.js View on Github external
firewall.services = {};
        firewall.enabledServices = new Set();

        if (!firewall.enabled) {
            firewall.dispatchEvent('changed');
            return;
        }

        /* As certain dbus signal callbacks might change the firewall frequently
         * in a short period of time, prevent rapid succession of renders by
         * debouncing the ('changed') event */
        firewall.debouncedEvent = debounce(300, event => firewall.dispatchEvent(event));

        /* As a service might be removed from multiple zones at the same time,
         * prevent rapid succession of GetServices call */
        firewall.debouncedGetServices = debounce(300, getServices);

        firewall.debouncedGetZones = debounce(300, () => {
            getZones()
                    .then(() => getServices())
                    .catch(error => console.warn(error));
        });

        getZones()
                .then(() => getServices())
                .catch(error => console.warn(error));
    });
github chakra-ui / chakra-ui / packages / hooks / src / useSlider / useSlider.tsx View on Github external
(event: React.PointerEvent) => {
      setIsPointerDown(false);

      if (trackRef.current) {
        trackRef.current.releasePointerCapture(event.pointerId);
      }

      if (onChangeEnd) {
        onChangeEnd(value);
      }
    },
    [onChangeEnd, value],
  );

  // throttle the pointer move function
  const log = throttle(100, (event?: any) => {
    // setIsHovering(true)
    const nextValue = getValueFromPointer(event);
    console.log(nextValue);
  });

  const onPointerLeave = () => {
    // setIsHovering(false)
  };

  const onPointerMove = (event: React.PointerEvent) => {
    event.persist();
    log(event);
    if (isPointerDown) {
      const nextValue = getValueFromPointer(event);
      if (nextValue !== value) {
        updateValue(nextValue);
github albinotonnina / react-truncate-string / src / truncateString.js View on Github external
component: this.componentRef.offsetWidth,
      ellipsis: this.ellipsisRef.offsetWidth,
      text: this.textRef.offsetWidth
    }

    const {ellipsisString} = this.props

    return truncateString({
      measurements,
      text,
      ellipsisString,
      leftPercentage: this.props.truncateAt
    })
  }

  resetTruncate = debounce(50, () => {
    // this renders the original string so we can measure it
    this.setState({truncating: true}, () => {
      // now we render again with the truncated string
      const truncatedString = this.getTruncateString(this.props.text)
      this.setState({truncatedString, truncating: false})
    })
  })

  componentDidMount() {
    // calculate  truncatedString and set state to render again with the truncated string
    const truncatedString = this.getTruncateString(this.props.text)
    this.setState({truncatedString, truncating: false})

    window.addEventListener('resize', this.resetTruncate)
  }
github dfinityexplorer / dfinityexplorer / web / src / Components / ResponsiveComponent / ResponsiveComponent.js View on Github external
constructor() {
    super();

    // Bind to make 'this' work in callbacks.
    this.handleWindowResize = this.handleWindowResize.bind(this);

    // Throttle the calls to handleWindowResize() so that we're not constantly re-rendering.
    this.throttledHandleWindowResize = throttle(200, true, this.handleWindowResize);
  }
github NullVoxPopuli / ember-three-boxes-demo / app / components / demo / -base-demo-component.js View on Github external
animate(updateCanvas) {
    let last = Date.now();
    let boundCallback;

    let fpsUpdate = () => {
      this.fps = Math.round(avg(this.frames));
    }
    let updateFps = throttle(120, fpsUpdate);

    function loop() {
      let rotations = this.appState.rotations;
      this.frame = requestAnimationFrame(boundCallback);

      for (let i = 0; i < rotations.length; i++) {

        // this.rotations[i].x += 0.01;
        // this.rotations[i].y += 0.01;
        // this.rotations[i].z += 0.01;
        let rotation = rotations[i];
        rotation.r = {
          x: rotation.r.x + 0.01,
          y: rotation.r.y + 0.01,
          z: rotation.r.z + 0.01,
        }
github nk-o / ghostkit / src / assets / js / script.js View on Github external
hasScrolled();
                } );
        } );

        // Set FS video size.
        const throttledSetFullscreenVideoSize = throttle( 200, () => {
            rafl( () => {
                self.setFullscreenVideoSize();
            } );
        } );
        $( window ).on( 'DOMContentLoaded load resize orientationchange', () => {
            throttledSetFullscreenVideoSize();
        } );

        // Init blocks.
        const throttledInitBlocks = throttle( 200, () => {
            rafl( () => {
                self.initBlocks();
            } );
        } );
        if ( window.MutationObserver ) {
            new window.MutationObserver( throttledInitBlocks )
                .observe( document.documentElement, {
                    childList: true, subtree: true,
                } );
        } else {
            $( document ).on( 'DOMContentLoaded DOMNodeInserted load', () => {
                throttledInitBlocks();
            } );
        }

        // Prepare hash changes.
github zhjing1019 / elementParse / packages / table / src / table-store.js View on Github external
selection: [],
    reserveSelection: false,
    selectable: null,
    currentRow: null,
    hoverRow: null,
    filters: {},
    expandRows: [],
    defaultExpandAll: false,
    selectOnIndeterminate: false,
    treeData: {},
    indent: 16,
    lazy: false,
    lazyTreeNodeMap: {}
  };

  this._toggleAllSelection = debounce(10, function(states) {
    const data = states.data || [];
    if (data.length === 0) return;
    const selection = this.states.selection;
    // when only some rows are selected (but not all), select or deselect all of them
    // depending on the value of selectOnIndeterminate
    const value = states.selectOnIndeterminate ? !states.isAllSelected : !(states.isAllSelected || selection.length);
    let selectionChanged = false;
    data.forEach((item, index) => {
      if (states.selectable) {
        if (states.selectable.call(null, item, index) && toggleRowSelection(states, item, value)) {
          selectionChanged = true;
        }
      } else {
        if (toggleRowSelection(states, item, value)) {
          selectionChanged = true;
        }
github ElemeFE / element / packages / table / src / store / helper.js View on Github external
export function createStore(table, initialState = {}) {
  if (!table) {
    throw new Error('Table is required.');
  }

  const store = new Store();
  store.table = table;
  // fix https://github.com/ElemeFE/element/issues/14075
  // related pr https://github.com/ElemeFE/element/pull/14146
  store.toggleAllSelection = debounce(10, store._toggleAllSelection);
  Object.keys(initialState).forEach(key => {
    store.states[key] = initialState[key];
  });
  return store;
}
github mhalle / oabrowser / src / ng-providers / crosshairProvider.js View on Github external
angular.module('atlasDemo').provider("crosshair", ["mainAppProvider", "volumesManagerProvider", function (mainAppProvider, volumesManagerProvider) {

    var singleton = {},
        volumesManager = volumesManagerProvider.$get(),
        mainApp = mainAppProvider.$get(),
        crosshairPosition = {},
        needUpdate =true,
        visible = false,
        mouseOverCrosshair = {},
        firebaseView,
        debouncedCommit = debounce(150, function () {
            if(firebaseView) {
                firebaseView.commit('crosshair');
            }
        });

    function computeCrosshairPosition () {
        var sagittal = volumesManager.compositingSlices.sagittal,
            coronal = volumesManager.compositingSlices.coronal,
            axial = volumesManager.compositingSlices.axial;
        if (axial && sagittal && coronal) {
            var dimensions = volumesManager.volumes[0].RASDimensions;
            crosshairPosition =  {
                coronal:[sagittal.index, axial.index],
                sagittal :[dimensions[2]-axial.index, dimensions[1]-coronal.index],
                axial :[sagittal.index, dimensions[1]-coronal.index]
            };
github bem / bem-react-components / blocks / Popup / _autovisible / Popup_autovisible.js View on Github external
willInit() {
        this.__base(...arguments);

        this._calcIsAnchorVisible = this._calcIsAnchorVisible.bind(this);
        this.onAnchorParentsScroll = throttle(100, this.onAnchorParentsScroll.bind(this));
        this.onViewportResize = throttle(100, this.onViewportResize.bind(this));
        this._bindToScroll = this._bindToScroll.bind(this);
        this._unbindFromScroll = this._unbindFromScroll.bind(this);
    },

throttle-debounce

Throttle and debounce functions.

MIT
Latest version published 2 years ago

Package Health Score

67 / 100
Full package analysis