JQuery Fade object after 20 seconds of inactivity

I want the div to disappear if the user has not clicked the mouse for 20 seconds.

I have the following code:

if($('.main-popup2').is(":visible")){ setTimeout(function() { $('.main-popup2').fadeOut('fast'); }, 20000); } 

The problem is that I do not know how to reset setTimeout after detecting a user click.

Thanks!

+4
source share
3 answers

Method . setTimeout () actually returns a reference to the timer it creates. This link can be used in .clearTimeout to stop the timer before executing it.

Here is an example of how to use it:

 var timer; if($('.main-popup2').is(":visible")){ // create the timer and save its reference timer = setTimeout(function() { $('.main-popup2').fadeOut('fast'); }, 20000); } // when clicking somewhere on the page, stop the timer $(document).click(function() { clearTimeout(timer); }): 
+7
source
 var timeout = null; var fadeElement = $('.main-popup2'); function fader() { if(null !== timeout) { clearTimeout(timeout); } fadeElement.stop(); timeout = setTimeout(function () {fadeElement.fadeOut('fast');}, 2000); } $(document).click(fader); fader(); 
+1
source

Use the delay function.

 (window).click(function () { $('.main-popup2').delay(6000).fadeOut(300); } 

Each click restarts 6 seconds after it starts .main-popup2, if not

+1
source

Source: https://habr.com/ru/post/1398228/


All Articles