skip to Main Content

I’m working on some projects and I was wondering why the setTimeout(s) I was delaying where taking a lot longer then expected…

To give a context, the code reacts to some triggers, and the function fires quite a lot (maybe like 15 times a second). on this function, I increment a global value, then do a setTimeout of 3 seconds and decrement the global value by the same amount (expecting it to be back to 0 after the maximum 3 seconds every timeout should take)

But apparently they have a way of working different from what I expected, and they sort of stack in time… so the global value decrement slowly.

code :


//trigger method... just fires like a button press in html
register("soundPlay", () => {
    addCount();
}).setCriteria("random.successful_hit");

var count = 0;

function addCount() {
    console.log("triggered");
    count+= 10;
    setTimeout(function () {
        count-= 10;
    }, 3000);
}

Here’s a result of the function after I stop triggering, the stacking is shown in the brackets. It shows every 1/20th of a second. So from the moment I stop it takes over 30 seconds to get down to zero.

results

Any ideas why? Any solutions or reason?

Ty 🙂

2

Answers


  1. You have to use debounce to get the effect you want

    var count = 0;
    
    b.onclick = addCount
    
    const clearCount = debounce(() => {
      setTimeout(function() {
        count = 0;
        console.log(count)
      }, 3000);
    }, 500)
    
    function addCount() {
      count += 10;
      console.log(count)
      clearCount()
    }
    
    function debounce(callback, wait) {
      let timeoutId = null;
      return (...args) => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          callback(...args);
        }, wait);
      };
    }
    <button id="b">add count</button>
    Login or Signup to reply.
  2. Your code works fine for me

    1. It adds 10 to count every 100ms (1s overall)
    2. It waits 3 seconds since the start (so 2s after the last one)
    3. It subtracts 10 from count every 100ms (1s overall)
    var count = 0;
    
    for (let i = 0; i < 10; i += 1) {
      setTimeout(addCount, i * 100)
    }
    
    function addCount() {
        count+= 10;
        console.log(count)
        setTimeout(function () {
            count-= 10;
            console.log(count)
        }, 3000);
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search