Search code examples
javascriptsliderconsole.log

output the last value of the function


I have a written slider function that, when clicked, displays all values in the console

function outputUpdate(vol) {
  let output = document.querySelector('#volume');
  output.value = vol;

  output.style.left = vol - 20 + 'px';
  if (output.value > 9) {
    output.style.left = vol - 30 + 'px';
  }
  if (output.value > 99) {
    output.style.left = vol - 40 + 'px';
  }
  if (output.value > 240) {
    output.style.left = vol - 45 + 'px';
  }
  if (output.value > 430) {
    output.style.left = vol - 50 + 'px';
  }
  if (output.value > 470) {
    output.style.left = vol - 55 + 'px';
  }
  console.log(vol)
}
<div class="slider">
  <output for="fader" id="volume">0</output>
  <input type="range" id="fader" min="0" max="600" value="0" step="1" oninput="outputUpdate(value)">
</div>

but I need to get only the last value from the console

I tried to write a loop inside the function, but it gives me all the values

      for(i= 0; i< output.value; i++){
             vol1 = vol;
        }
        console.log(vol1)

Current output: output added a picture, I need to get only the final value in the console (i.e. in this case 46) and not all values


Solution

    • From @Pointy's suggestion.
    • We have added property to outputUpdate, function. F.Y.I, function is an object in javascript so we can add as many properties as we want, here we have created timerId property to store id, initialized it with default value 0, to avoid TypeError, because clearTimeout() function expects, valid Id.

    function outputUpdate(vol) {
      let output = document.querySelector('#volume');
      output.value = vol;
      output.style.left = vol - 20 + 'px';
      if (output.value > 9) {
        output.style.left = vol - 30 + 'px';
      }
      if (output.value > 99) {
        output.style.left = vol - 40 + 'px';
      }
      if (output.value > 240) {
        output.style.left = vol - 45 + 'px';
      }
      if (output.value > 430) {
        output.style.left = vol - 50 + 'px';
      }
      if (output.value > 470) {
        output.style.left = vol - 55 + 'px';
      }
    
      // Clear any existing timer and create a new one to print the value
      clearTimeout(outputUpdate.timerId);
      outputUpdate.timerId = setTimeout(() => {
        console.log(vol);
      }, 500);
    }
    // Initialize the timerId property to 0
    outputUpdate.timerId = 0;
    <div class="slider">
      <output for="fader" id="volume">0</output>
      <input type="range" id="fader" min="0" max="600" value="0" step="1" oninput="outputUpdate(value)">
    </div>