1

I am showing and hiding some modals by altering their CSS properties. I want them to be displayed until there is no key event in last 3 seconds. Is there a way to handle this via JavaScript? VueJs solutions would be better.

I am currently hiding the modal after 3 seconds like this :

   

 function a(){
    document.querySelector("#playPause").style.display = "block";
                  setTimeout(() => {
                    document.querySelector("#playPause").style.display = "none";
                  }, 3000);
    }
#playPause{
     display:none;
      background-color:black;
    }
<button onclick="a()">Display</button>
<div id="playPause">EXAMPLE</div>
AEB
  • 125
  • 9
  • 1
    [Debounce](https://stackoverflow.com/a/4298672/1169519) a keyup listener ..? – Teemu Mar 18 '20 at 11:26
  • @Teemu Is there any working example of it? – AEB Mar 18 '20 at 11:36
  • edited the post @Teemu. onclick instead of click – Bastian Springer Mar 18 '20 at 11:37
  • There's an example in the linked post, just attach keyup instead of resize. BGerrissen's code works also with `addEventListener`, just call `debounce` and pass it your listener function instead of passing the function directly. – Teemu Mar 18 '20 at 11:37
  • 1
    @AEB thanks for editing that removing/hiding back. I needed to change 6 characters, so *on*click wasn't enough of a change – Bastian Springer Mar 18 '20 at 12:15

1 Answers1

2

Save the timeout as a variable and clear it before setting it again:

   

var timeout;
function a(){
    clearTimeout (timeout);
    document.querySelector("#playPause").style.display = "block";
    timeout = setTimeout(() => {
        document.querySelector("#playPause").style.display = "none";
    }, 3000);
}
#playPause{
     display:none;
      background-color:black;
    }
<button onclick="a()">Display</button>
<div id="playPause">EXAMPLE</div>
Bastian Springer
  • 271
  • 2
  • 11