On page load, we should wait 15 seconds and then start checking for user activity in the form of mouse movement. If there is user activity, fire code and start waiting 15 seconds for user activity again.
My best shot is below. I have made an interval that gives permission to check every 15 seconds, and another interval that checks for permission and tries to fire the code on first mouse movement, then reset permission -- every second.
The initial check is correct (it waits 15 seconds and doesn't fire until the mouse moves), but then the code keeps firing every 15 seconds regardless of user activity -- though oddly enough only when the window is in focus. I suspect my error is in the mousemove bit, but I'm not sure.
var allow = false;
setInterval(permission, 15000);
function permission() {
if (allow == false){
allow = true;
}
}
setInterval(function() {
$('body').one('mousemove', function() {
if (allow == true){
alert("code firing");
allow = false;
$('body').off( "mousemove" )
}
});
}, 1000);
You should use setTimeout
for this, because the interval you need is not constant: you don't know when the user will move their mouse and the 15 second period should start from 0 again.
Here is a demo with 3 second waits (to test it quickly):
var allow;
function lockUp() {
allow = false;
$('#output').text("No permission for 3 seconds!");
setTimeout(function () {
$('#output').text("Permission!");
allow = true;
}, 3000);
}
// start by locking for 3 secs
lockUp();
$(document).on('mousemove', function() {
if (!allow) return; // not allowed
lockUp();
// Perform the action here...
// ...
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>