Rdang
Rdang

Reputation: 131

How to start mouse movement action triggering script after countdown?

I have a script that redirects to a php page after mouse movement is detected, but I only want to trigger this script 3 seconds after page starts loading.

At the moment I have this :

<script>

var myListener = setTimeout(function () {
document.removeEventListener('mousemove', myListener, false);
window.location = 'index.php';
}, 3000);

document.addEventListener('mousemove', myListener, false);
</script>   

The problem is this is redirecting to the php file no matter what, while if I remove the timeout it will only redirect if mouse movement detected.

How to do this properly ?

Upvotes: 0

Views: 53

Answers (1)

Julian
Julian

Reputation: 424

I think you're almost there.. try this:

<script>

    var myListener = function() {
        window.location = 'index.php';
    }

    setTimeout(function () {
        document.addEventListener('mousemove', myListener, false);
    }, 3000);

</script>   

The function passed into setTimeout is getting executed 3 seconds after the page load, so we wait until this triggers in order to add the event listener for the mouse moving. That way all mouse events that happen before three seconds are ignored.

Upvotes: 2

Related Questions