Oğuzcan Budumlu
Oğuzcan Budumlu

Reputation: 619

Getting last value of slider

I am using HTML slider (type="range"). It updates relevant element for each intermediate value while going to target value. Because it is a big data rendering project, it causes the application to slow down. I want it to take only for its last value, not intermediate values.

I'm using this element in a React project. I have encountered that MaterialUI has onChangeCommitted event but I do not want to use an external library.

Is there any way to simulate this onChangeCommitted?

Upvotes: 0

Views: 1168

Answers (2)

Drew Reese
Drew Reese

Reputation: 203418

Using an onChange handler on an uncontrolled input slider to manage a debounced "expensive" callback, you can utilize setTimeout to call the real callback once expired. Upon every change event reset the timeout. Use a ref to store the timer id.

const [value, setValue] = useState(0);
const timerRef = useRef();

const expensiveCallback = value => {
  console.log('expensiveCallback', value);
  setValue(value); // <-- finally update state, or anything else really
};

const changeHandler = (e) => {
  const { value } = e.target;

  clearTimeout(timerRef.current);
  timerRef.current = setTimeout(() => {
    expensiveCallback(value); // <-- re-enclose latest value
  }, 250); // <-- tune this value to what feels best for you
};

return (
  ...

    <input
      type="range"
      min={0}
      max={1000}
      defaultValue={value} // <-- use default value for uncontrolled input
      onChange={changeHandler}
    />

  ...
);

Edit getting-last-value-of-slider

Upvotes: 1

Prashant Sani
Prashant Sani

Reputation: 456

You can use the step attribute to mention how much user can increment the range value. For instance, we can make 1 as start value and 100 as the last value and step=100 which will only allow the user to increase value from 0 to 100.

  <input type="range" id="volume" name="volume"
         min="1" max="100" step="100">
  <label for="volume">Volume</label>

Upvotes: 0

Related Questions