0

In reactJS I want to resize a div according to the mouse position. I don't want to call the render method for every event. How can I add a kind of delay, that prevents a render for aech mouse event?

reactJS

 ...
 resizeChild(e) {

      //add delay

      this.setState({
        width: e.positionX,
      }
 ...


<body onMouseMove={this.resizeChild}>
  <div style={{width: this.state.width}}>
   Resize me
  </div>
</body>
vuvu
  • 4,886
  • 12
  • 50
  • 73
  • i think debounce is more appropriate in this case. by the way you can look at [this](http://demo.nimius.net/debounce_throttle/) demo example which shows exactly how using debounce against throttle with mouse moves – Sagiv b.g Jan 02 '18 at 14:48

1 Answers1

1

You can use debounce for that. Some javascript libraries provide this functionality, however you could write your own.

The following is taken from lodash:

Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If immediate is passed, trigger the function on the leading edge, instead of the trailing.

and the code:

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

This means that if you import lodash as _, you could do:

<body onMouseMove={_.debounce(this.resizeChild, 500)}>

this will only trigger the resizeChild function twice per second at most.

Chris
  • 57,622
  • 19
  • 111
  • 137
  • What is args = arguments for, it is never set. debounce(this.resizeChild, 500) calls resizeChild immediately. How can I make it work? – vuvu Jan 02 '18 at 15:36
  • @vuvu, the larger code snippet is just the source code taken from lodash in case you want to see how it works. If you are implementing the library, just do the last snippet. – Chris Jan 02 '18 at 15:40
  • I tried the last snippet and debounce says: Uncaught TypeError: Expected a function. – vuvu Jan 02 '18 at 15:48
  • @vuvu are you sure you copied the code as is? Including the underscore and dot? Did you do `import _ from lodash;` and installed lodash from npm? – Chris Jan 02 '18 at 15:50