简体   繁体   中英

Javascript setTimeout on Mouseleave event

I have a div that appears when the user's mouse leaves the document with a survey about my site.

I don't want to ask them to do the survey if they move their mouse out in the first couple of minutes while browsing around, so I was wondering if I can set a timeout/sleep on when this mouseleave function would activate.

Here is my code without the timeout:

        $(document).mouseleave(function () {
        document.getElementById("Overlay1").style.display = "";
        });

Thanks a lot!

You can use window.setTimeout to enable the function after a certain time.

Example:

    window.setTimeout(function(){
    $(document).mouseleave(function () {
            console.log('mouse leave');
            document.getElementById("Overlay1").style.display = "";
            });
        console.log('initiated');
    },5000);

you could call the same function encapsulated in a setTimeout function call:

 $(document).mouseleave(function() {
    var seconds = 3;

    //execute the function in 3 seconds
    setTimeout(function(){
        document.getElementById("Overlay1").style.display = "";
    },seconds*1000);
 });

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