Home > OS >  Change timeout when number finishes counting
Change timeout when number finishes counting

Time:09-18

have a question on how to set the timeout to 0 when counting is finished, that way after the counting is finished to immediately proceed to process3 and skip the timeout that was set before.

Because if i want to set a bigger number or smaller the counting finishes faster or take too long and you have to set the timeout exactly as the number. But i want to make people choose the number, and can't set static number on the timeout.

number = 100;

function startprocess() {
  let p1 = setTimeout(process1, 0);
  let p2 = setTimeout(process2, 2000);
  let p3 = setTimeout(process3, 20000);

  function process1() {
    document.getElementById("counting").innerHTML = "Starting with count";
  }

  function process2() {
    document.getElementById("counting").innerHTML = number;
    document.getElementById("counting").innerHTML = "Count Started";

    function constant(duration, range, current) {
      return duration / range;
    }

    function animateValue(id, start, duration, easing) {
      var end = parseInt(number, 10);
      var range = (end - start)   start;
      var current = start;
      var increment = end > start ? 1 : -1;
      var obj = document.getElementById("number");
      var startTime = new Date();
      var offset = 1;
      var remainderTime = 0;

      var step = function() {
        current  = increment;
        obj.innerHTML = current;

        if (current != end) {
          setTimeout(step, easing(duration, range, current));
        } else {
          setTimeout(p3, 0);
        }
      };

      setTimeout(step, easing(duration, range, start));
    }
    animateValue("number", 0, 10000, constant);
  }

  function process3() {
    document.getElementById("counting").innerHTML = "Count Finished";
  }
}
<div>
  <span id="number" style="font-weight: 900; font-size: large; color: black; "></span> </div>

<div id="counting"> </div>

<button id="start" onclick="startprocess()"> Start </button>

CodePudding user response:

Generally speaking, you will get the timeoutId when setting the timeout and with that you should be able to cancel the timeout by calling clearTimeout(timeoutId)

const timeoutId = setTimeout(() => { console.log("Timeout reached") }, 5000);
clearTimeout(timeoutId); // Timeout is cancelled

So if you need to run the function immediately, just cancel the timeout and call the function right away

  • Related