0

I'm building a website that allows users to give input, and I want to prevent a function from running before certain time. In this case, I want that time to be 2 seconds. I've been trying to use a setTimeout function to control the delay, and I've been having issues. Through the use of 'console.log()', I've been able to figure out that the issue is that toggleCanRun() is never called. Can anyone explain why? Thank you so much. Here's the code I've got so far

function toggleCanRun () {
    canRun = true;
    clearTimeout(timer);
};
let timer;
let canRun = true;
function playSound () {
    if (canRun === true) {
        displayInfo();
        canRun = false;
        timer = setTimeout(toggleCanRun, 2000);
    } else {
        clearTimeout(timer);
    };
};
User 10
  • 177
  • 3
  • 10
  • Looks like you want a `debounced` function here. Lots of js helper libraries have a debounce function helper (Like underscore/[lodash](https://lodash.com/docs#debounce), etc.) – Garrett Motzner Apr 17 '20 at 23:13
  • Does this answer your question? [What does \_.debounce do?](https://stackoverflow.com/questions/15927371/what-does-debounce-do) – Garrett Motzner Apr 17 '20 at 23:15
  • I've already installed several other libraries for this project, and I'm trying to keep the size down. Genhis has given me an answer that works without an additional library, so thanks for your help, but I think I'll stick with what they suggested – User 10 Apr 17 '20 at 23:20

1 Answers1

0

When the function can't run (canRun = false) and you call playSound(), it executes else condition and clears the timeout, which is why it doesn't get executed.

If you remove the else condition, it should work correctly. The timeout is one-time only, so you don't need to clear it anywhere.

function playSound () {
    if (canRun === true) {
        displayInfo();
        canRun = false;
        timer = setTimeout(toggleCanRun, 2000);
    }
};
Genhis
  • 1,484
  • 3
  • 27
  • 29