最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery Fade object after 20 seconds of inactivity - Stack Overflow

programmeradmin1浏览0评论

I want to fade out a div if a user hasn't made a mouse click for 20 seconds.

I have the following code:

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

Problem is I don't know how to reset the setTimeout after detecting a user mouse click.

Thanks!

I want to fade out a div if a user hasn't made a mouse click for 20 seconds.

I have the following code:

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

Problem is I don't know how to reset the setTimeout after detecting a user mouse click.

Thanks!

Share Improve this question asked Feb 24, 2012 at 12:54 jribeirojribeiro 3,4739 gold badges44 silver badges70 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

The .setTimeout() method actually returns a reference to the timer it creates. This reference can be used in .clearTimeout to stop the timer before it executes.

Here is an example of how to use this:

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);
}):
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();

Use delay function.

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

Each click restart 6 seconds, after it .main-popup2 fadeout if there isn't

发布评论

评论列表(0)

  1. 暂无评论