Time Slider in Javascript

Viewed 319

I am having a slider here. Below is the code of its function:

const [durationPercentage, setDurationPercentage] = useState(0);
const [maxDuration, setMaxDuration] = useState("06:00");

  useEffect(() => {
    const durationMax = maxDuration.replace(":", "");

    const duration = (Number(durationMax) * durationPercentage) / 100;

    var a = String(duration);
    var b = ":";
    var position = String(duration).length - 2;
    var output = [a.slice(0, position), b, a.slice(position)].join("");
    console.log(output);
  }, [durationPercentage]);


   /*========== Slider ===============*/

    <Slider
      onChange={(event, newDurationPercentage) =>
       setDurationPercentage(newDurationPercentage)
      }
    />

When I slides the slider, I am getting the result(s): enter image description here

But, as you can see, after the : there are numbers greater than 60. When the numbers greater than or equal to 60 comes, I want the minute to increase by 1.
That is: When the slider slides, I want the result to be actually a valid time. Like: 01:04, 07:55 and not: 04:79, 01:88. The format would be mm:ss format.
Any help is greatly apperciated!

2 Answers

I think if you instead store your durationPercentage and maxDuration as number values it makes the math easier, and converting a value from one unit to others becomes a trivial matter.

Solution

Store all number values in seconds.

  • To convert seconds to whole minutes: seconds / 60 and floor
  • To compute seconds remainder: seconds mod 60
  • Convert the results to a String padded to length 2 with "0" to pad out to two "digits".

Code

const [durationPercentage, setDurationPercentage] = useState(0);
const [maxDuration, setMaxDuration] = useState(360);

useEffect(() => {
  const duration = Math.floor((maxDuration * durationPercentage) / 100);

  const minutes = Math.floor(duration / 60);
  const seconds = duration % 60;

  const output = `${String(minutes).padStart(2, 0)}:${String(
    seconds
  ).padStart(2, 0)}`;

  console.log(output);
}, [durationPercentage, maxDuration]);

Demo

Edit time-slider-in-javascript

enter image description here

Here is the fixed code.

const [durationPercentage, setDurationPercentage] = useState(0);
const [maxDuration, setMaxDuration] = useState("06:00");

useEffect(() => {
    const maxMinuteSecond = maxDuration.split(":");
    const durationMax = Number(maxMinuteSecond[0]) * 60 + Number(maxMinuteSecond[1]);

    const duration = (Number(durationMax) * durationPercentage) / 100;

    var second = duration % 60;
    var minute = (duration - second) / 60;// Math.floor(duration / 60);
    
    var output = (minute<10?"0":"") + minute.toString() + ":" + (second<10?"0":"") + second.toString();;
    console.log(output);
}, [durationPercentage]);
Related