简体   繁体   中英

Using setTimeout() to delay an event

This is a working function that I've been using to add/remove a class to a separate element immediately when one element has been hovered on:

$(document).ready(function() {     
    $('.mm-parent:not(.mm-active)').hover(function(){      
        $('.mm-active').addClass('activefix');    
    },     
    function(){    
        $('.mm-active').removeClass('activefix');     
    });
});

However, I'm trying to:

  • Delay it from adding the class until 1 second has passed.
  • Also have it remove the class after its own 1 second has passed.

I don't know if I'm on the right track, but here is what I have:

$(document).ready.setTimeout(function() {     
    $('.mm-parent:not(.mm-active)').hover(function(){     
        $('.mm-active').addClass('activefix');    
    },     
    function(){    
        $('.mm-active').removeClass('activefix');     
    }, 1000);
});

Try

$(document).ready(function () {
    var timer;
    $('.mm-parent:not(.mm-active)').hover(function () {
        clearTimeout(timer);
        timer = setTimeout(function () {
            $('.mm-active').addClass('activefix');
        }, 1000)
    }, function () {
        clearTimeout(timer);
        timer = setTimeout(function () {
            $('.mm-active').removeClass('activefix');
        }, 1000)
    });
});

Try this

$(document).ready(function() {     
   $('.mm-parent:not(.mm-active)').hover(function(){      
        setTimeout(function(){
                $('.mm-active').addClass('activefix'); 
                setTimeout(function(){$('.mm-active').removeClass('activefix');},1000);
        },1000);

    });    
});

Basically you have to run a function 1 sec after hover which internally runs one more function after 1 sec.

JsFiddle http://jsfiddle.net/L8B73/

Use CSS transition,that might serve your need.

 -webkit-transition: all 1s ease-out;  /* Chrome 1-25, Safari 3.2+ */
 -moz-transition: all 1s ease-out;  /* Firefox 4-15 */
 -o-transition: all 1s ease-out;  /* Opera 10.50–12.00 */
 transition: all 1s ease-out; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM