How to detect idle time in JavaScript - javascript

Is it possible to detect "idle" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.
I define idle time as a period of user inactivity or without any CPU usage

Here is a simple script using jQuery that handles mousemove and keypress events.
If the time expires, the page reloads.
<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
// Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
// Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 19) { // 20 minutes
window.location.reload();
}
}
</script>

With vanilla JavaScript:
var inactivityTime = function () {
var time;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeydown = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.html'
}
function resetTimer() {
clearTimeout(time);
time = setTimeout(logout, 3000)
// 1000 milliseconds = 1 second
}
};
And initialise the function where you need it (for example: onPageLoad).
window.onload = function() {
inactivityTime();
}
You can add more DOM events if you need to. Most used are:
document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer; // touchscreen presses
document.ontouchstart = resetTimer;
document.onclick = resetTimer; // touchpad clicks
document.onkeydown = resetTimer; // onkeypress is deprectaed
document.addEventListener('scroll', resetTimer, true); // improved; see comments
Or register desired events using an array
window.addEventListener('load', resetTimer, true);
var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
events.forEach(function(name) {
document.addEventListener(name, resetTimer, true);
});
DOM Events list: http://www.w3schools.com/jsref/dom_obj_event.asp
Remember to use window, or document according your needs. Here you can see the differences between them: What is the difference between window, screen, and document in JavaScript?
Code Updated with #frank-conijn and #daxchen improve: window.onscroll will not fire if scrolling is inside a scrollable element, because scroll events don't bubble. In window.addEventListener('scroll', resetTimer, true), the third argument tells the listener to catch the event during the capture phase instead of the bubble phase.

Improving on Equiman's (original) answer:
function idleLogout() {
var t;
window.onload = resetTimer;
window.onmousemove = resetTimer;
window.onmousedown = resetTimer; // catches touchscreen presses as well
window.ontouchstart = resetTimer; // catches touchscreen swipes as well
window.ontouchmove = resetTimer; // required by some devices
window.onclick = resetTimer; // catches touchpad clicks as well
window.onkeydown = resetTimer;
window.addEventListener('scroll', resetTimer, true); // improved; see comments
function yourFunction() {
// your function for too long inactivity goes here
// e.g. window.location.href = 'logout.php';
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(yourFunction, 10000); // time is in milliseconds
}
}
idleLogout();
Apart from the improvements regarding activity detection, and the change from document to window, this script actually calls the function, rather than letting it sit idle by.
It doesn't catch zero CPU usage directly, but that is impossible, because executing a function causes CPU usage. And user inactivity eventually leads to zero CPU usage, so indirectly it does catch zero CPU usage.

I have created a small library that does this:
https://github.com/shawnmclean/Idle.js
Description:
Tiny JavaScript library to report activity of user in the browser
(away, idle, not looking at webpage, in a different tab, etc). that is independent of any
other JavaScript libraries such as jQuery.
Visual Studio users can get it from NuGet by:
Install-Package Idle.js

Here is a rough jQuery implementation of tvanfosson's idea:
$(document).ready(function(){
idleTime = 0;
//Increment the idle time counter every second.
var idleInterval = setInterval(timerIncrement, 1000);
function timerIncrement()
{
idleTime++;
if (idleTime > 2)
{
doPreload();
}
}
//Zero the idle timer on mouse movement.
$(this).mousemove(function(e){
idleTime = 0;
});
function doPreload()
{
//Preload images, etc.
}
})

Similar to Peter J's solution (with a jQuery custom event)...
// Use the jquery-idle-detect.js script below
$(window).on('idle:start', function() {
// Start your prefetch, etc. here...
});
$(window).on('idle:stop', function() {
// Stop your prefetch, etc. here...
});
File jquery-idle-detect.js
(function($, $w) {
// Expose configuration option
// Idle is triggered when no events for 2 seconds
$.idleTimeout = 2000;
// Currently in idle state
var idle = false;
// Handle to idle timer for detection
var idleTimer = null;
// Start the idle timer and bind events on load (not DOM-ready)
$w.on('load', function() {
startIdleTimer();
$w.on('focus resize mousemove keyup', startIdleTimer)
.on('blur', idleStart) // Force idle when in a different tab/window
;
]);
function startIdleTimer() {
clearTimeout(idleTimer); // Clear prior timer
if (idle) $w.trigger('idle:stop'); // If idle, send stop event
idle = false; // Not idle
var timeout = ~~$.idleTimeout; // Option to integer
if (timeout <= 100)
timeout = 100; // Minimum 100 ms
if (timeout > 300000)
timeout = 300000; // Maximum 5 minutes
idleTimer = setTimeout(idleStart, timeout); // New timer
}
function idleStart() {
if (!idle)
$w.trigger('idle:start');
idle = true;
}
}(window.jQuery, window.jQuery(window)))

You can do it more elegantly with Underscore.js and jQuery:
$('body').on("click mousemove keyup", _.debounce(function(){
// do preload here
}, 1200000)) // 20 minutes debounce

My answer was inspired by vijay's answer, but is a shorter, more general solution that I thought I'd share for anyone it might help.
(function () {
var minutes = true; // change to false if you'd rather use seconds
var interval = minutes ? 60000 : 1000;
var IDLE_TIMEOUT = 3; // 3 minutes in this example
var idleCounter = 0;
document.onmousemove = document.onkeypress = function () {
idleCounter = 0;
};
window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
window.location.reload(); // or whatever you want to do
}
}, interval);
}());
As it currently stands, this code will execute immediately and reload your current page after 3 minutes of no mouse movement or key presses.
This utilizes plain vanilla JavaScript and an immediately-invoked function expression to handle idle timeouts in a clean and self-contained manner.

All the previous answers have an always-active mousemove handler. If the handler is jQuery, the additional processing jQuery performs can add up. Especially if the user is using a gaming mouse, as many as 500 events per second can occur.
This solution avoids handling every mousemove event. This result in a small timing error, but which you can adjust to your need.
function setIdleTimeout(millis, onIdle, onUnidle) {
var timeout = 0;
startTimer();
function startTimer() {
timeout = setTimeout(onExpires, millis);
document.addEventListener("mousemove", onActivity);
document.addEventListener("keydown", onActivity);
document.addEventListener("touchstart", onActivity);
}
function onExpires() {
timeout = 0;
onIdle();
}
function onActivity() {
if (timeout) clearTimeout(timeout);
else onUnidle();
//since the mouse is moving, we turn off our event hooks for 1 second
document.removeEventListener("mousemove", onActivity);
document.removeEventListener("keydown", onActivity);
document.removeEventListener("touchstart", onActivity);
setTimeout(startTimer, 1000);
}
}
http://jsfiddle.net/9exz43v2/

I had the same issue and I found a quite good solution.
I used jquery.idle and I only needed to do:
$(document).idle({
onIdle: function(){
alert('You did nothing for 5 seconds');
},
idle: 5000
})
See JsFiddle demo.
(Just for information: see this for back-end event tracking Leads browserload)

If you are targeting a supported browser (Chrome or Firefox as of December 2018) you can experiment with the requestIdleCallback and include the requestIdleCallback shim for unsupported browsers.

You could probably hack something together by detecting mouse movement on the body of the form and updating a global variable with the last movement time. You'd then need to have an interval timer running that periodically checks the last movement time and does something if it has been sufficiently long since the last mouse movement was detected.

I wrote a small ES6 class to detect activity and otherwise fire events on idle timeout. It covers keyboard, mouse and touch, can be activated and deactivated and has a very lean API:
const timer = new IdleTimer(() => alert('idle for 1 minute'), 1000 * 60 * 1);
timer.activate();
It does not depend on jQuery, though you might need to run it through Babel to support older browsers.
https://gist.github.com/4547ef5718fd2d31e5cdcafef0208096

(Partially inspired by the good core logic of Equiman's answer.)
sessionExpiration.js
sessionExpiration.js is lightweight yet effective and customizable. Once implemented, use in just one row:
sessionExpiration(idleMinutes, warningMinutes, logoutUrl);
Affects all tabs of the browser, not just one.
Written in pure JavaScript, with no dependencies. Fully client side.
(If so wanted.) Has warning banner and countdown clock, that is cancelled by user interaction.
Simply include the sessionExpiration.js, and call the function, with arguments [1] number of idle minutes (across all tabs) until user is logged out, [2] number of idle minutes until warning and countdown is displayed, and [3] logout url.
Put the CSS in your stylesheet. Customize it if you like. (Or skip and delete banner if you don't want it.)
If you do want the warning banner however, then you must put an empty div with ID sessExpirDiv on your page (a suggestion is putting it in the footer).
Now the user will be logged out automatically if all tabs have been inactive for the given duration.
Optional: You may provide a fourth argument (URL serverRefresh) to the function, so that a server side session timer is also refreshed when you interact with the page.
This is an example of what it looks like in action, if you don't change the CSS.

Try this code. It works perfectly.
var IDLE_TIMEOUT = 10; //seconds
var _idleSecondsCounter = 0;
document.onclick = function () {
_idleSecondsCounter = 0;
};
document.onmousemove = function () {
_idleSecondsCounter = 0;
};
document.onkeypress = function () {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
alert("Time expired!");
document.location.href = "SessionExpired.aspx";
}
}

<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$('body').mousemove(function (e) {
//alert("mouse moved" + idleTime);
idleTime = 0;
});
$('body').keypress(function (e) {
//alert("keypressed" + idleTime);
idleTime = 0;
});
$('body').click(function() {
//alert("mouse moved" + idleTime);
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 10) { // 10 minutes
window.location.assign("http://www.google.com");
}
}
</script>
I think this jQuery code is perfect one, though copied and modified from above answers!!
Do not forgot to include the jQuery library in your file!

Pure JavaScript with a properly set reset time and bindings via addEventListener:
(function() {
var t,
timeout = 5000;
function resetTimer() {
console.log("reset: " + new Date().toLocaleString());
if (t) {
window.clearTimeout(t);
}
t = window.setTimeout(logout, timeout);
}
function logout() {
console.log("done: " + new Date().toLocaleString());
}
resetTimer();
//And bind the events to call `resetTimer()`
["click", "mousemove", "keypress"].forEach(function(name) {
console.log(name);
document.addEventListener(name, resetTimer);
});
}());

The problem with all these solutions, although correct, is they are impractical, when taking into account the session timeout valuable set, using PHP, .NET or in the Application.cfc file for ColdFusion developers.
The time set by the above solution needs to sync with the server-side session timeout. If the two do not sync, you can run into problems that will just frustrate and confuse your users.
For example, the server side session timeout might be set to 60 minutes, but the user may believe that he/she is safe, because the JavaScript idle time capture has increased the total amount of time a user can spend on a single page. The user may have spent time filling in a long form, and then goes to submit it. The session timeout might kick in before the form submission is processed.
I tend to just give my users 180 minutes, and then use JavaScript to automatically log the user out. Essentially, using some of the code above, to create a simple timer, but without the capturing mouse event part.
In this way my client side and server-side time syncs perfectly. There is no confusion, if you show the time to the user in your UI, as it reduces. Each time a new page is accessed in the CMS, the server side session and JavaScript timer are reset. Simple and elegant. If a user stays on a single page for more than 180 minutes, I figure there is something wrong with the page, in the first place.

You can use the below mentioned solution
var idleTime;
$(document).ready(function () {
reloadPage();
$('html').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
clearTimeout(idleTime);
reloadPage();
});
});
function reloadPage() {
clearTimeout(idleTime);
idleTime = setTimeout(function () {
location.reload();
}, 3000);
}

I wrote a simple jQuery plugin that will do what you are looking for.
https://github.com/afklondon/jquery.inactivity
$(document).inactivity( {
interval: 1000, // the timeout until the inactivity event fire [default: 3000]
mouse: true, // listen for mouse inactivity [default: true]
keyboard: false, // listen for keyboard inactivity [default: true]
touch: false, // listen for touch inactivity [default: true]
customEvents: "customEventName", // listen for custom events [default: ""]
triggerAll: true, // if set to false only the first "activity" event will be fired [default: false]
});
The script will listen for mouse, keyboard, touch and other custom events inactivity (idle) and fire global "activity" and "inactivity" events.

I have tested this code working file:
var timeout = null;
var timee = '4000'; // default time for session time out.
$(document).bind('click keyup mousemove', function(event) {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
timeout = null;
console.log('Document Idle since '+timee+' ms');
alert("idle window");
}, timee);
});

Is it possible to have a function run every 10 seconds, and have that check a "counter" variable? If that's possible, you can have an on mouseover for the page, can you not?
If so, use the mouseover event to reset the "counter" variable. If your function is called, and the counter is above the range that you pre-determine, then do your action.

Here is the best solution I have found:
Fire Event When User is Idle
Here is the JavaScript:
idleTimer = null;
idleState = false;
idleWait = 2000;
(function ($) {
$(document).ready(function () {
$('*').bind('mousemove keydown scroll', function () {
clearTimeout(idleTimer);
if (idleState == true) {
// Reactivated event
$("body").append("<p>Welcome Back.</p>");
}
idleState = false;
idleTimer = setTimeout(function () {
// Idle Event
$("body").append("<p>You've been idle for " + idleWait/1000 + " seconds.</p>");
idleState = true; }, idleWait);
});
$("body").trigger("mousemove");
});
}) (jQuery)

I use this approach, since you don't need to constantly reset the time when an event fires. Instead, we just record the time, and this generates the idle start point.
function idle(WAIT_FOR_MINS, cb_isIdle) {
var self = this,
idle,
ms = (WAIT_FOR_MINS || 1) * 60000,
lastDigest = new Date(),
watch;
//document.onmousemove = digest;
document.onkeypress = digest;
document.onclick = digest;
function digest() {
lastDigest = new Date();
}
// 1000 milisec = 1 sec
watch = setInterval(function() {
if (new Date() - lastDigest > ms && cb_isIdel) {
clearInterval(watch);
cb_isIdle();
}
}, 1000*60);
},

Based on the inputs provided by equiman:
class _Scheduler {
timeoutIDs;
constructor() {
this.timeoutIDs = new Map();
}
addCallback = (callback, timeLapseMS, autoRemove) => {
if (!this.timeoutIDs.has(timeLapseMS + callback)) {
let timeoutID = setTimeout(callback, timeLapseMS);
this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
}
if (autoRemove !== false) {
setTimeout(
this.removeIdleTimeCallback, // Remove
10000 + timeLapseMS, // 10 secs after
callback, // the callback
timeLapseMS, // is invoked.
);
}
};
removeCallback = (callback, timeLapseMS) => {
let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
if (timeoutID) {
clearTimeout(timeoutID);
this.timeoutIDs.delete(timeLapseMS + callback);
}
};
}
class _IdleTimeScheduler extends _Scheduler {
events = [
'load',
'mousedown',
'mousemove',
'keydown',
'keyup',
'input',
'scroll',
'touchstart',
'touchend',
'touchcancel',
'touchmove',
];
callbacks;
constructor() {
super();
this.events.forEach(name => {
document.addEventListener(name, this.resetTimer, true);
});
this.callbacks = new Map();
}
addIdleTimeCallback = (callback, timeLapseMS) => {
this.addCallback(callback, timeLapseMS, false);
let callbacksArr = this.callbacks.get(timeLapseMS);
if (!callbacksArr) {
this.callbacks.set(timeLapseMS, [callback]);
} else {
if (!callbacksArr.includes(callback)) {
callbacksArr.push(callback);
}
}
};
removeIdleTimeCallback = (callback, timeLapseMS) => {
this.removeCallback(callback, timeLapseMS);
let callbacksArr = this.callbacks.get(timeLapseMS);
if (callbacksArr) {
let index = callbacksArr.indexOf(callback);
if (index !== -1) {
callbacksArr.splice(index, 1);
}
}
};
resetTimer = () => {
for (let [timeLapseMS, callbacksArr] of this.callbacks) {
callbacksArr.forEach(callback => {
// Clear the previous IDs
let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
clearTimeout(timeoutID);
// Create new timeout IDs.
timeoutID = setTimeout(callback, timeLapseMS);
this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
});
}
};
}
export const Scheduler = new _Scheduler();
export const IdleTimeScheduler = new _IdleTimeScheduler();

As simple as it can get, detect when the mouse moves only:
var idle = false;
document.querySelector('body').addEventListener('mousemove', function(e) {
if(idle!=false)
idle = false;
});
var idleI = setInterval(function()
{
if(idle == 'inactive')
{
return;
}
if(idle == true)
{
idleFunction();
idle = 'inactive';
return;
}
idle = true;
}, 30000); // half the expected time. Idle will trigger after 60 s in this case.
function idleFuntion()
{
console.log('user is idle');
}

Here is an AngularJS service for accomplishing in Angular.
/* Tracks now long a user has been idle. secondsIdle can be polled
at any time to know how long user has been idle. */
fuelServices.factory('idleChecker',['$interval', function($interval){
var self = {
secondsIdle: 0,
init: function(){
$(document).mousemove(function (e) {
self.secondsIdle = 0;
});
$(document).keypress(function (e) {
self.secondsIdle = 0;
});
$interval(function(){
self.secondsIdle += 1;
}, 1000)
}
}
return self;
}]);
Keep in mind this idle checker will run for all routes, so it should be initialized in .run() on load of the angular app. Then you can use idleChecker.secondsIdle inside each route.
myApp.run(['idleChecker',function(idleChecker){
idleChecker.init();
}]);

Surely you want to know about window.requestIdleCallback(), which queues a function to be called during a browser's idle periods.
You can see an elegant usage of this API in the Quicklink repo.
const requestIdleCallback = window.requestIdleCallback ||
function (cb) {
const start = Date.now();
return setTimeout(function () {
cb({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start));
},
});
}, 1);
};
The meaning of the code above is: if the browser supports requestIdleCallback (check the compatibility), uses it. If is not supported, uses a setTimeout(()=> {}, 1) as fallback, which should queue the function to be called at the end of the event loop.
Then you can use it like this:
requestIdleCallback(() => {...}, {
timeout: 2000
});
The second parameter is optional, you might want to set a timeout if you want to make sure the function is executed.

You could probably detect inactivity on your web page using the mousemove tricks listed, but that won't tell you that the user isn't on another page in another window or tab, or that the user is in Word or Photoshop, or WoW and just isn't looking at your page at this time.
Generally, I'd just do the prefetch and rely on the client's multi-tasking. If you really need this functionality, you do something with an ActiveX control in Windows, but it's ugly at best.

Debounce is actually a great idea! Here is a version for jQuery-free projects:
const derivedLogout = createDerivedLogout(30);
derivedLogout(); // It could happen that the user is too idle)
window.addEventListener('click', derivedLogout, false);
window.addEventListener('mousemove', derivedLogout, false);
window.addEventListener('keyup', derivedLogout, false);
function createDerivedLogout (sessionTimeoutInMinutes) {
return _.debounce( () => {
window.location = this.logoutUrl;
}, sessionTimeoutInMinutes * 60 * 1000 )
}

Related

I want to show an alert to the user after no activity for a specific time without using setTimeout function in jquery, is there a way to tackle this? [duplicate]

Is it possible to detect "idle" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.
I define idle time as a period of user inactivity or without any CPU usage
Here is a simple script using jQuery that handles mousemove and keypress events.
If the time expires, the page reloads.
<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
// Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
// Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 19) { // 20 minutes
window.location.reload();
}
}
</script>
With vanilla JavaScript:
var inactivityTime = function () {
var time;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeydown = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.html'
}
function resetTimer() {
clearTimeout(time);
time = setTimeout(logout, 3000)
// 1000 milliseconds = 1 second
}
};
And initialise the function where you need it (for example: onPageLoad).
window.onload = function() {
inactivityTime();
}
You can add more DOM events if you need to. Most used are:
document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer; // touchscreen presses
document.ontouchstart = resetTimer;
document.onclick = resetTimer; // touchpad clicks
document.onkeydown = resetTimer; // onkeypress is deprectaed
document.addEventListener('scroll', resetTimer, true); // improved; see comments
Or register desired events using an array
window.addEventListener('load', resetTimer, true);
var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
events.forEach(function(name) {
document.addEventListener(name, resetTimer, true);
});
DOM Events list: http://www.w3schools.com/jsref/dom_obj_event.asp
Remember to use window, or document according your needs. Here you can see the differences between them: What is the difference between window, screen, and document in JavaScript?
Code Updated with #frank-conijn and #daxchen improve: window.onscroll will not fire if scrolling is inside a scrollable element, because scroll events don't bubble. In window.addEventListener('scroll', resetTimer, true), the third argument tells the listener to catch the event during the capture phase instead of the bubble phase.
Improving on Equiman's (original) answer:
function idleLogout() {
var t;
window.onload = resetTimer;
window.onmousemove = resetTimer;
window.onmousedown = resetTimer; // catches touchscreen presses as well
window.ontouchstart = resetTimer; // catches touchscreen swipes as well
window.ontouchmove = resetTimer; // required by some devices
window.onclick = resetTimer; // catches touchpad clicks as well
window.onkeydown = resetTimer;
window.addEventListener('scroll', resetTimer, true); // improved; see comments
function yourFunction() {
// your function for too long inactivity goes here
// e.g. window.location.href = 'logout.php';
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(yourFunction, 10000); // time is in milliseconds
}
}
idleLogout();
Apart from the improvements regarding activity detection, and the change from document to window, this script actually calls the function, rather than letting it sit idle by.
It doesn't catch zero CPU usage directly, but that is impossible, because executing a function causes CPU usage. And user inactivity eventually leads to zero CPU usage, so indirectly it does catch zero CPU usage.
I have created a small library that does this:
https://github.com/shawnmclean/Idle.js
Description:
Tiny JavaScript library to report activity of user in the browser
(away, idle, not looking at webpage, in a different tab, etc). that is independent of any
other JavaScript libraries such as jQuery.
Visual Studio users can get it from NuGet by:
Install-Package Idle.js
Here is a rough jQuery implementation of tvanfosson's idea:
$(document).ready(function(){
idleTime = 0;
//Increment the idle time counter every second.
var idleInterval = setInterval(timerIncrement, 1000);
function timerIncrement()
{
idleTime++;
if (idleTime > 2)
{
doPreload();
}
}
//Zero the idle timer on mouse movement.
$(this).mousemove(function(e){
idleTime = 0;
});
function doPreload()
{
//Preload images, etc.
}
})
Similar to Peter J's solution (with a jQuery custom event)...
// Use the jquery-idle-detect.js script below
$(window).on('idle:start', function() {
// Start your prefetch, etc. here...
});
$(window).on('idle:stop', function() {
// Stop your prefetch, etc. here...
});
File jquery-idle-detect.js
(function($, $w) {
// Expose configuration option
// Idle is triggered when no events for 2 seconds
$.idleTimeout = 2000;
// Currently in idle state
var idle = false;
// Handle to idle timer for detection
var idleTimer = null;
// Start the idle timer and bind events on load (not DOM-ready)
$w.on('load', function() {
startIdleTimer();
$w.on('focus resize mousemove keyup', startIdleTimer)
.on('blur', idleStart) // Force idle when in a different tab/window
;
]);
function startIdleTimer() {
clearTimeout(idleTimer); // Clear prior timer
if (idle) $w.trigger('idle:stop'); // If idle, send stop event
idle = false; // Not idle
var timeout = ~~$.idleTimeout; // Option to integer
if (timeout <= 100)
timeout = 100; // Minimum 100 ms
if (timeout > 300000)
timeout = 300000; // Maximum 5 minutes
idleTimer = setTimeout(idleStart, timeout); // New timer
}
function idleStart() {
if (!idle)
$w.trigger('idle:start');
idle = true;
}
}(window.jQuery, window.jQuery(window)))
You can do it more elegantly with Underscore.js and jQuery:
$('body').on("click mousemove keyup", _.debounce(function(){
// do preload here
}, 1200000)) // 20 minutes debounce
My answer was inspired by vijay's answer, but is a shorter, more general solution that I thought I'd share for anyone it might help.
(function () {
var minutes = true; // change to false if you'd rather use seconds
var interval = minutes ? 60000 : 1000;
var IDLE_TIMEOUT = 3; // 3 minutes in this example
var idleCounter = 0;
document.onmousemove = document.onkeypress = function () {
idleCounter = 0;
};
window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
window.location.reload(); // or whatever you want to do
}
}, interval);
}());
As it currently stands, this code will execute immediately and reload your current page after 3 minutes of no mouse movement or key presses.
This utilizes plain vanilla JavaScript and an immediately-invoked function expression to handle idle timeouts in a clean and self-contained manner.
All the previous answers have an always-active mousemove handler. If the handler is jQuery, the additional processing jQuery performs can add up. Especially if the user is using a gaming mouse, as many as 500 events per second can occur.
This solution avoids handling every mousemove event. This result in a small timing error, but which you can adjust to your need.
function setIdleTimeout(millis, onIdle, onUnidle) {
var timeout = 0;
startTimer();
function startTimer() {
timeout = setTimeout(onExpires, millis);
document.addEventListener("mousemove", onActivity);
document.addEventListener("keydown", onActivity);
document.addEventListener("touchstart", onActivity);
}
function onExpires() {
timeout = 0;
onIdle();
}
function onActivity() {
if (timeout) clearTimeout(timeout);
else onUnidle();
//since the mouse is moving, we turn off our event hooks for 1 second
document.removeEventListener("mousemove", onActivity);
document.removeEventListener("keydown", onActivity);
document.removeEventListener("touchstart", onActivity);
setTimeout(startTimer, 1000);
}
}
http://jsfiddle.net/9exz43v2/
I had the same issue and I found a quite good solution.
I used jquery.idle and I only needed to do:
$(document).idle({
onIdle: function(){
alert('You did nothing for 5 seconds');
},
idle: 5000
})
See JsFiddle demo.
(Just for information: see this for back-end event tracking Leads browserload)
If you are targeting a supported browser (Chrome or Firefox as of December 2018) you can experiment with the requestIdleCallback and include the requestIdleCallback shim for unsupported browsers.
You could probably hack something together by detecting mouse movement on the body of the form and updating a global variable with the last movement time. You'd then need to have an interval timer running that periodically checks the last movement time and does something if it has been sufficiently long since the last mouse movement was detected.
I wrote a small ES6 class to detect activity and otherwise fire events on idle timeout. It covers keyboard, mouse and touch, can be activated and deactivated and has a very lean API:
const timer = new IdleTimer(() => alert('idle for 1 minute'), 1000 * 60 * 1);
timer.activate();
It does not depend on jQuery, though you might need to run it through Babel to support older browsers.
https://gist.github.com/4547ef5718fd2d31e5cdcafef0208096
(Partially inspired by the good core logic of Equiman's answer.)
sessionExpiration.js
sessionExpiration.js is lightweight yet effective and customizable. Once implemented, use in just one row:
sessionExpiration(idleMinutes, warningMinutes, logoutUrl);
Affects all tabs of the browser, not just one.
Written in pure JavaScript, with no dependencies. Fully client side.
(If so wanted.) Has warning banner and countdown clock, that is cancelled by user interaction.
Simply include the sessionExpiration.js, and call the function, with arguments [1] number of idle minutes (across all tabs) until user is logged out, [2] number of idle minutes until warning and countdown is displayed, and [3] logout url.
Put the CSS in your stylesheet. Customize it if you like. (Or skip and delete banner if you don't want it.)
If you do want the warning banner however, then you must put an empty div with ID sessExpirDiv on your page (a suggestion is putting it in the footer).
Now the user will be logged out automatically if all tabs have been inactive for the given duration.
Optional: You may provide a fourth argument (URL serverRefresh) to the function, so that a server side session timer is also refreshed when you interact with the page.
This is an example of what it looks like in action, if you don't change the CSS.
Try this code. It works perfectly.
var IDLE_TIMEOUT = 10; //seconds
var _idleSecondsCounter = 0;
document.onclick = function () {
_idleSecondsCounter = 0;
};
document.onmousemove = function () {
_idleSecondsCounter = 0;
};
document.onkeypress = function () {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
alert("Time expired!");
document.location.href = "SessionExpired.aspx";
}
}
<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$('body').mousemove(function (e) {
//alert("mouse moved" + idleTime);
idleTime = 0;
});
$('body').keypress(function (e) {
//alert("keypressed" + idleTime);
idleTime = 0;
});
$('body').click(function() {
//alert("mouse moved" + idleTime);
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 10) { // 10 minutes
window.location.assign("http://www.google.com");
}
}
</script>
I think this jQuery code is perfect one, though copied and modified from above answers!!
Do not forgot to include the jQuery library in your file!
Pure JavaScript with a properly set reset time and bindings via addEventListener:
(function() {
var t,
timeout = 5000;
function resetTimer() {
console.log("reset: " + new Date().toLocaleString());
if (t) {
window.clearTimeout(t);
}
t = window.setTimeout(logout, timeout);
}
function logout() {
console.log("done: " + new Date().toLocaleString());
}
resetTimer();
//And bind the events to call `resetTimer()`
["click", "mousemove", "keypress"].forEach(function(name) {
console.log(name);
document.addEventListener(name, resetTimer);
});
}());
The problem with all these solutions, although correct, is they are impractical, when taking into account the session timeout valuable set, using PHP, .NET or in the Application.cfc file for ColdFusion developers.
The time set by the above solution needs to sync with the server-side session timeout. If the two do not sync, you can run into problems that will just frustrate and confuse your users.
For example, the server side session timeout might be set to 60 minutes, but the user may believe that he/she is safe, because the JavaScript idle time capture has increased the total amount of time a user can spend on a single page. The user may have spent time filling in a long form, and then goes to submit it. The session timeout might kick in before the form submission is processed.
I tend to just give my users 180 minutes, and then use JavaScript to automatically log the user out. Essentially, using some of the code above, to create a simple timer, but without the capturing mouse event part.
In this way my client side and server-side time syncs perfectly. There is no confusion, if you show the time to the user in your UI, as it reduces. Each time a new page is accessed in the CMS, the server side session and JavaScript timer are reset. Simple and elegant. If a user stays on a single page for more than 180 minutes, I figure there is something wrong with the page, in the first place.
You can use the below mentioned solution
var idleTime;
$(document).ready(function () {
reloadPage();
$('html').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
clearTimeout(idleTime);
reloadPage();
});
});
function reloadPage() {
clearTimeout(idleTime);
idleTime = setTimeout(function () {
location.reload();
}, 3000);
}
I wrote a simple jQuery plugin that will do what you are looking for.
https://github.com/afklondon/jquery.inactivity
$(document).inactivity( {
interval: 1000, // the timeout until the inactivity event fire [default: 3000]
mouse: true, // listen for mouse inactivity [default: true]
keyboard: false, // listen for keyboard inactivity [default: true]
touch: false, // listen for touch inactivity [default: true]
customEvents: "customEventName", // listen for custom events [default: ""]
triggerAll: true, // if set to false only the first "activity" event will be fired [default: false]
});
The script will listen for mouse, keyboard, touch and other custom events inactivity (idle) and fire global "activity" and "inactivity" events.
I have tested this code working file:
var timeout = null;
var timee = '4000'; // default time for session time out.
$(document).bind('click keyup mousemove', function(event) {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
timeout = null;
console.log('Document Idle since '+timee+' ms');
alert("idle window");
}, timee);
});
Is it possible to have a function run every 10 seconds, and have that check a "counter" variable? If that's possible, you can have an on mouseover for the page, can you not?
If so, use the mouseover event to reset the "counter" variable. If your function is called, and the counter is above the range that you pre-determine, then do your action.
Here is the best solution I have found:
Fire Event When User is Idle
Here is the JavaScript:
idleTimer = null;
idleState = false;
idleWait = 2000;
(function ($) {
$(document).ready(function () {
$('*').bind('mousemove keydown scroll', function () {
clearTimeout(idleTimer);
if (idleState == true) {
// Reactivated event
$("body").append("<p>Welcome Back.</p>");
}
idleState = false;
idleTimer = setTimeout(function () {
// Idle Event
$("body").append("<p>You've been idle for " + idleWait/1000 + " seconds.</p>");
idleState = true; }, idleWait);
});
$("body").trigger("mousemove");
});
}) (jQuery)
I use this approach, since you don't need to constantly reset the time when an event fires. Instead, we just record the time, and this generates the idle start point.
function idle(WAIT_FOR_MINS, cb_isIdle) {
var self = this,
idle,
ms = (WAIT_FOR_MINS || 1) * 60000,
lastDigest = new Date(),
watch;
//document.onmousemove = digest;
document.onkeypress = digest;
document.onclick = digest;
function digest() {
lastDigest = new Date();
}
// 1000 milisec = 1 sec
watch = setInterval(function() {
if (new Date() - lastDigest > ms && cb_isIdel) {
clearInterval(watch);
cb_isIdle();
}
}, 1000*60);
},
Based on the inputs provided by equiman:
class _Scheduler {
timeoutIDs;
constructor() {
this.timeoutIDs = new Map();
}
addCallback = (callback, timeLapseMS, autoRemove) => {
if (!this.timeoutIDs.has(timeLapseMS + callback)) {
let timeoutID = setTimeout(callback, timeLapseMS);
this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
}
if (autoRemove !== false) {
setTimeout(
this.removeIdleTimeCallback, // Remove
10000 + timeLapseMS, // 10 secs after
callback, // the callback
timeLapseMS, // is invoked.
);
}
};
removeCallback = (callback, timeLapseMS) => {
let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
if (timeoutID) {
clearTimeout(timeoutID);
this.timeoutIDs.delete(timeLapseMS + callback);
}
};
}
class _IdleTimeScheduler extends _Scheduler {
events = [
'load',
'mousedown',
'mousemove',
'keydown',
'keyup',
'input',
'scroll',
'touchstart',
'touchend',
'touchcancel',
'touchmove',
];
callbacks;
constructor() {
super();
this.events.forEach(name => {
document.addEventListener(name, this.resetTimer, true);
});
this.callbacks = new Map();
}
addIdleTimeCallback = (callback, timeLapseMS) => {
this.addCallback(callback, timeLapseMS, false);
let callbacksArr = this.callbacks.get(timeLapseMS);
if (!callbacksArr) {
this.callbacks.set(timeLapseMS, [callback]);
} else {
if (!callbacksArr.includes(callback)) {
callbacksArr.push(callback);
}
}
};
removeIdleTimeCallback = (callback, timeLapseMS) => {
this.removeCallback(callback, timeLapseMS);
let callbacksArr = this.callbacks.get(timeLapseMS);
if (callbacksArr) {
let index = callbacksArr.indexOf(callback);
if (index !== -1) {
callbacksArr.splice(index, 1);
}
}
};
resetTimer = () => {
for (let [timeLapseMS, callbacksArr] of this.callbacks) {
callbacksArr.forEach(callback => {
// Clear the previous IDs
let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
clearTimeout(timeoutID);
// Create new timeout IDs.
timeoutID = setTimeout(callback, timeLapseMS);
this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
});
}
};
}
export const Scheduler = new _Scheduler();
export const IdleTimeScheduler = new _IdleTimeScheduler();
As simple as it can get, detect when the mouse moves only:
var idle = false;
document.querySelector('body').addEventListener('mousemove', function(e) {
if(idle!=false)
idle = false;
});
var idleI = setInterval(function()
{
if(idle == 'inactive')
{
return;
}
if(idle == true)
{
idleFunction();
idle = 'inactive';
return;
}
idle = true;
}, 30000); // half the expected time. Idle will trigger after 60 s in this case.
function idleFuntion()
{
console.log('user is idle');
}
Here is an AngularJS service for accomplishing in Angular.
/* Tracks now long a user has been idle. secondsIdle can be polled
at any time to know how long user has been idle. */
fuelServices.factory('idleChecker',['$interval', function($interval){
var self = {
secondsIdle: 0,
init: function(){
$(document).mousemove(function (e) {
self.secondsIdle = 0;
});
$(document).keypress(function (e) {
self.secondsIdle = 0;
});
$interval(function(){
self.secondsIdle += 1;
}, 1000)
}
}
return self;
}]);
Keep in mind this idle checker will run for all routes, so it should be initialized in .run() on load of the angular app. Then you can use idleChecker.secondsIdle inside each route.
myApp.run(['idleChecker',function(idleChecker){
idleChecker.init();
}]);
Surely you want to know about window.requestIdleCallback(), which queues a function to be called during a browser's idle periods.
You can see an elegant usage of this API in the Quicklink repo.
const requestIdleCallback = window.requestIdleCallback ||
function (cb) {
const start = Date.now();
return setTimeout(function () {
cb({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start));
},
});
}, 1);
};
The meaning of the code above is: if the browser supports requestIdleCallback (check the compatibility), uses it. If is not supported, uses a setTimeout(()=> {}, 1) as fallback, which should queue the function to be called at the end of the event loop.
Then you can use it like this:
requestIdleCallback(() => {...}, {
timeout: 2000
});
The second parameter is optional, you might want to set a timeout if you want to make sure the function is executed.
You could probably detect inactivity on your web page using the mousemove tricks listed, but that won't tell you that the user isn't on another page in another window or tab, or that the user is in Word or Photoshop, or WoW and just isn't looking at your page at this time.
Generally, I'd just do the prefetch and rely on the client's multi-tasking. If you really need this functionality, you do something with an ActiveX control in Windows, but it's ugly at best.
Debounce is actually a great idea! Here is a version for jQuery-free projects:
const derivedLogout = createDerivedLogout(30);
derivedLogout(); // It could happen that the user is too idle)
window.addEventListener('click', derivedLogout, false);
window.addEventListener('mousemove', derivedLogout, false);
window.addEventListener('keyup', derivedLogout, false);
function createDerivedLogout (sessionTimeoutInMinutes) {
return _.debounce( () => {
window.location = this.logoutUrl;
}, sessionTimeoutInMinutes * 60 * 1000 )
}

Method runs multiple times [duplicate]

I want to trigger an ajax request when the user has finished typing in a text box. I don't want it to run the function on every time the user types a letter because that would result in A LOT of ajax requests, however I don't want them to have to hit the enter button either.
Is there a way so I can detect when the user has finished typing and then do the ajax request?
Using jQuery here!
So, I'm going to guess finish typing means you just stop for a while, say 5 seconds. So with that in mind, let's start a timer when the user releases a key and clear it when they press one. I decided the input in question will be #myInput.
Making a few assumptions...
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 seconds for example
var $input = $('#myInput');
//on keyup, start the countdown
$input.on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$input.on('keydown', function () {
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
//do something
}
The chosen answer above does not work.
Because typingTimer is occassionaly set multiple times (keyup pressed twice before keydown is triggered for fast typers etc.) then it doesn't clear properly.
The solution below solves this problem and will call X seconds after finished as the OP requested. It also no longer requires the redundant keydown function. I have also added a check so that your function call won't happen if your input is empty.
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms (5 seconds)
//on keyup, start the countdown
$('#myInput').keyup(function(){
clearTimeout(typingTimer);
if ($('#myInput').val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
//user is "finished typing," do something
function doneTyping () {
//do something
}
And the same code in vanilla JavaScript solution:
//setup before functions
let typingTimer; //timer identifier
let doneTypingInterval = 5000; //time in ms (5 seconds)
let myInput = document.getElementById('myInput');
//on keyup, start the countdown
myInput.addEventListener('keyup', () => {
clearTimeout(typingTimer);
if (myInput.value) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
//user is "finished typing," do something
function doneTyping () {
//do something
}
This solution does use ES6 but it's not necessary here. Just replace let with var and the arrow function with a regular function.
It's just one line with underscore.js debounce function:
$('#my-input-box').keyup(_.debounce(doSomething , 500));
This basically says doSomething 500 milliseconds after I stop typing.
For more info: http://underscorejs.org/#debounce
Late answer but I'm adding it because it's 2019 and this is entirely achievable using pretty ES6, no third party libraries, and I find most of the highly rated answers are bulky and weighed down with too many variables.
Elegant solution taken from this excellent blog post.
function debounce(callback, wait) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(function () { callback.apply(this, args); }, wait);
};
}
window.addEventListener('keyup', debounce( () => {
// code you would like to run 1000ms after the keyup event has stopped firing
// further keyup events reset the timer, as expected
}, 1000))
Yes, you can set a timeout of say 2 seconds on each and every key up event which will fire an ajax request. You can also store the XHR method and abort it on subsequent key press events so that you save bandwith even more. Here's something I've written for an autocomplete script of mine.
var timer;
var x;
$(".some-input").keyup(function () {
if (x) { x.abort() } // If there is an existing XHR, abort it.
clearTimeout(timer); // Clear the timer so we don't end up with dupes.
timer = setTimeout(function() { // assign timer a new timeout
x = $.getJSON(...); // run ajax request and store in x variable (so we can cancel)
}, 2000); // 2000ms delay, tweak for faster/slower
});
Hope this helps,
Marko
var timer;
var timeout = 1000;
$('#in').keyup(function(){
clearTimeout(timer);
if ($('#in').val) {
timer = setTimeout(function(){
//do stuff here e.g ajax call etc....
var v = $("#in").val();
$("#out").html(v);
}, timeout);
}
});
full example here: http://jsfiddle.net/ZYXp4/8/
Both top 2 answers doesn't work for me. So, here is my solution:
var timeout = null;
$('#myInput').keyup(function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
//do stuff here
}, 500);
});
Declare the following delay function:
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})()
and then use it:
let $filter = $('#item-filter');
$filter.on('keydown', function () {
delay(function () {
console.log('this will hit, once user has not typed for 1 second');
}, 1000);
});
Modifying the accepted answer to handle additional cases such as paste:
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 2000; //time in ms, 2 second for example
var $input = $('#myInput');
// updated events
$input.on('input propertychange paste', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//user is "finished typing," do something
function doneTyping () {
//do something
}
I like Surreal Dream's answer but I found that my "doneTyping" function would fire for every keypress, i.e. if you type "Hello" really quickly; instead of firing just once when you stop typing, the function would fire 5 times.
The problem was that the javascript setTimeout function doesn't appear to overwrite or kill the any old timeouts that have been set, but if you do it yourself it works! So I just added a clearTimeout call just before the setTimeout if the typingTimer is set. See below:
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
//on keyup, start the countdown
$('#myInput').on("keyup", function(){
if (typingTimer) clearTimeout(typingTimer); // Clear if already set
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#myInput').on("keydown", function(){
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
//do something
}
N.B. I would have liked to have just added this as a comment to Surreal Dream's answer but I'm a new user and don't have enough reputation. Sorry!
I don't think keyDown event is necessary in this case (please tell me why if I'm wrong). In my (non-jquery) script similar solution looks like that:
var _timer, _timeOut = 2000;
function _onKeyUp(e) {
clearTimeout(_timer);
if (e.keyCode == 13) { // close on ENTER key
_onCloseClick();
} else { // send xhr requests
_timer = window.setTimeout(function() {
_onInputChange();
}, _timeOut)
}
}
It's my first reply on Stack Overflow, so I hope this helps someone, someday:)
const inText = document.getElementById('inText')
const outText = document.getElementById('outText')
const delay = 1000
let timer
inText.addEventListener('input', code => {
clearTimeout(timer);
timer = setTimeout(x => {
outText.innerHTML = inText.value
}, delay, code)
})
<textarea id='inText'>edit this and...</textarea>
<pre id='outText'>see the results after you stop typing for one second</pre>
Well, strictly speaking no, as the computer cannot guess when the user has finished typing. You could of course fire a timer on key up, and reset it on every subsequent key up. If the timer expires, the user hasn't typed for the timer duration - you could call that "finished typing".
If you expect users to make pauses while typing, there's no way to know when they are done.
(Unless of course you can tell from the data when they are done)
agree with the #going 's answer. Another similar solution that worked for me is the one below. The only difference is that I am using .on("input"...) instead of keyup. This only captures changes in the input. other keys like Ctrl, Shift etc. are ignored
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms (5 seconds)
//on input change, start the countdown
$('#myInput').on("input", function() {
clearTimeout(typingTimer);
typingTimer = setTimeout(function(){
// doSomething...
}, doneTypingInterval);
});
I was implementing the search at my listing and needed it to be ajax based. That means that on every key change, searched results should be updated and displayed. This results in so many ajax calls sent to server, which is not a good thing.
After some working, I made an approach to ping the server when the user stops typing.
This solution worked for me:
$(document).ready(function() {
$('#yourtextfield').keyup(function() {
s = $('#yourtextfield').val();
setTimeout(function() {
if($('#yourtextfield').val() == s){ // Check the value searched is the latest one or not. This will help in making the ajax call work when client stops writing.
$.ajax({
type: "POST",
url: "yoururl",
data: 'search=' + s,
cache: false,
beforeSend: function() {
// loading image
},
success: function(data) {
// Your response will come here
}
})
}
}, 1000); // 1 sec delay to check.
}); // End of keyup function
}); // End of document.ready
You will notice that there is no need to use any timer while implementing this.
I feel like the solution is somewhat a bit simpler with the input event:
var typingTimer;
var doneTypingInterval = 500;
$("#myInput").on("input", function () {
window.clearTimeout(typingTimer);
typingTimer = window.setTimeout(doneTyping, doneTypingInterval);
});
function doneTyping () {
// code here
}
I just figured out a simple code to wait for user to finish typing:
step 1.set time out to null then clear the current timeout when the user is typing.
step 2.trigger clear timeout to the variable define before keyup event is triggered.
step 3.define timeout to the variable declared above;
<input type="text" id="input" placeholder="please type" style="padding-left:20px;"/>
<div class="data"></div>
javascript code
var textInput = document.getElementById('input');
var textdata = document.querySelector('.data');
// Init a timeout variable to be used below
var timefired = null;
// Listen for keystroke events
// Init a timeout variable to be used below
var timefired = null;// Listen for keystroke events
textInput.onkeyup = function (event) {
clearTimeout(timefired);
timefired = setTimeout(function () {
textdata.innerHTML = 'Input Value:'+ textInput.value;
}, 600);
};
This is the a simple JS code I wrote:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head><title>Submit after typing finished</title>
<script language="javascript" type="text/javascript">
function DelayedSubmission() {
var date = new Date();
initial_time = date.getTime();
if (typeof setInverval_Variable == 'undefined') {
setInverval_Variable = setInterval(DelayedSubmission_Check, 50);
}
}
function DelayedSubmission_Check() {
var date = new Date();
check_time = date.getTime();
var limit_ms=check_time-initial_time;
if (limit_ms > 800) { //Change value in milliseconds
alert("insert your function"); //Insert your function
clearInterval(setInverval_Variable);
delete setInverval_Variable;
}
}
</script>
</head>
<body>
<input type="search" onkeyup="DelayedSubmission()" id="field_id" style="WIDTH: 100px; HEIGHT: 25px;" />
</body>
</html>
Why not just use onfocusout?
https://www.w3schools.com/jsreF/event_onfocusout.asp
If it's a form, they will always leave focus of every input field in order to click the submit button so you know no input will miss out on getting its onfocusout event handler called.
Multiple timers per page
All the other answers only work for one control (my other answer included).
If you have multiple controls per page (e.g. in a shopping cart) only the last control where the user typed something will get called. In my case this is certainly not the wished behaviour - each control should have its own timer.
To solve this, you simply have to pass an ID to the function and maintain a timeoutHandles dictionary as in the following code:
Function Declaration:
var delayUserInput = (function () {
var timeoutHandles = {};
return function (id, callback, ms) {
if (timeoutHandles[id]) {
clearTimeout(timeoutHandles[id]);
}
timeoutHandles[id] = setTimeout(callback, ms);
};
})();
Function Usage:
delayUserInput('yourID', function () {
//do some stuff
}, 1000);
Here is a solution that fires after 1 second of not typing, but also fires instantly when the input is blank. This is useful when clearing search results after the user deletes the input query. This solution also supports copying and pasting into the search box. The $(() => { ... }); wrapping the top portion of code simply means "do this when the page is loaded" in simple Jquery terms.
var searchTimer;
var searchInterval = 1000;
$(() => {
$('#search-box').on('input', (event) => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
searchContacts(event.target.value);
}, (event.target.value.length > 0) ? searchInterval : 0);
});
});
function searchContacts(val) {
console.log('searching: ' + val);
}
You can use the onblur event to detect when the textbox loses focus:
https://developer.mozilla.org/en/DOM/element.onblur
That's not the same as "stops typing", if you care about the case where the user types a bunch of stuff and then sits there with the textbox still focused.
For that I would suggest tying a setTimeout to the onclick event, and assuming that after x amount of time with no keystrokes, the user has stopped typing.
If there is necessity for the user to move away from the field, we can use "onBlur" instead of Onchange in Javascript
<TextField id="outlined-basic" variant="outlined" defaultValue={CardValue} onBlur={cardTitleFn} />
If that is not necessary setting timer would be the good option.
for alpine.js users <input #input.debounce.500ms="fn()">
Once you detect focus on the text box, on key up do a timeout check, and reset it each time it's triggered.
When the timeout completes, do your ajax request.
If you are looking for a specific length (such as a zipcode field):
$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
//make ajax request here after.
}
});
Not sure if my needs are just kind of weird, but I needed something similar to this and this is what I ended up using:
$('input.update').bind('sync', function() {
clearTimeout($(this).data('timer'));
$.post($(this).attr('data-url'), {value: $(this).val()}, function(x) {
if(x.success != true) {
triggerError(x.message);
}
}, 'json');
}).keyup(function() {
clearTimeout($(this).data('timer'));
var val = $.trim($(this).val());
if(val) {
var $this = $(this);
var timer = setTimeout(function() {
$this.trigger('sync');
}, 2000);
$(this).data('timer', timer);
}
}).blur(function() {
clearTimeout($(this).data('timer'));
$(this).trigger('sync');
});
Which allows me to have elements like this in my application:
<input type="text" data-url="/controller/action/" class="update">
Which get updated when the user is "done typing" (no action for 2 seconds) or goes to another field (blurs out of the element)
If you need wait until user is finished with typing use simple this:
$(document).on('change','#PageSize', function () {
//Do something after new value in #PageSize
});
Complete Example with ajax call - this working for my pager - count of item per list:
$(document).ready(function () {
$(document).on('change','#PageSize', function (e) {
e.preventDefault();
var page = 1;
var pagesize = $("#PageSize").val();
var q = $("#q").val();
$.ajax({
url: '#Url.Action("IndexAjax", "Materials", new { Area = "TenantManage" })',
data: { q: q, pagesize: pagesize, page: page },
type: 'post',
datatype: "json",
success: function (data) {
$('#tablecontainer').html(data);
// toastr.success('Pager has been changed', "Success!");
},
error: function (jqXHR, exception) {
ShowErrorMessage(jqXHR, exception);
}
});
});
});
Simple and easy to understand.
var mySearchTimeout;
$('#ctl00_mainContent_CaseSearch').keyup(function () {
clearTimeout(mySearchTimeout);
var filter = $(this).val();
mySearchTimeout = setTimeout(function () { myAjaxCall(filter); }, 700);
return true;
});
For passing parameters to your function along with ES6 syntax.
$(document).ready(() => {
let timer = null;
$('.classSelector').keydown(() => {
clearTimeout(timer);
timer = setTimeout(() => foo('params'), 500);
});
});
const foo = (params) => {
console.log(`In foo ${params}`);
}

Suspend setTimeout refresh function when client is idle. Enable function when client is active

An existing refresh function that I don't wan't to touch (if possible). It refreshes a table in page.
I need to suspend the refresh function if the client is idle / inactive.
If the client is active the original refresh function returns to the way it was before being suspended.
//SUSPEND THIS FUNCTION IF CLIENT IS IDLE
//ENABLE THIS FUNCTION WHEN CLIENT IS ACTIVE
function refreshTable() {
window.clearTimeout(timer);
timer = window.setTimeout(refreshTable, 5000);
$("body").append("<p>refreshTable every 5 seconds.</p>");
}
var timer = window.setTimeout(refreshTable, 0);
function idleClientCheck() {
var t;
window.onload = resetTimer;
window.onmousemove = resetTimer;
window.onmousedown = resetTimer;
window.onclick = resetTimer;
window.onscroll = resetTimer;
window.onkeypress = resetTimer;
function isNotIdle() {
setTimeout(timer);
//alert('isNotIdle');
}
function isIdle() {
clearTimeout(timer);
alert('isIdle');
}
function resetTimer() {
clearTimeout(t);
//MY LOGIC ERROR
t = setInterval(isNotIdle, 9999);
//THIS WORKS LIKE I WANT. BUT refreshTable() DOES NOT
//RESTART AGAIN WHEN CLIENT IS ACTIVE
t = setInterval(isIdle, 15000);
}
}
idleClientCheck();
Codepen
Your code can be easily refactored into something that makes a bit more sense, when you realized that all your need is two timers:
Timer 1, say refreshTimer, simply iteratively invokes itself to refresh the table
Timer 2, say idleTimer, checks how long the user has been idle. This timer is reset whenever a specific event is fired from the window object, as per your question's requirements
Basic timer settings
With that in mind, we can set up two global timers:
// Global timers
var refreshTimer = null,
idleTimer = null;
We can also store the timeouts somewhere, so that they don't clutter our functions with magic constants :) refreshDuration is the interval you want to call the refresh function, while idleDuration is the duration you use to determine if the user is inactive:
// Some settings
var refreshDuration = 5000, // You can change this!
idleDuration = 3000; // You can change this!
p/s: You have noted in your question that you wanted to wait for 15s (i.e. 15000ms), but for testing purposes I have reduced it.
The refresh timer: self-invoking function that refreshes content
To mimic a window.setInterval function for the freshTimer callback, we simply define a refresh() function, which within itself starts a new timeout and invokes itself again:
var refresh = function() {
$("body").append("<p>refreshTable every 5 second.</p>");
// Call itself
refreshTimer = window.setTimeout(refresh, refreshDuration);
};
The idle timer: checking for user (in)activity
For the idle timer, what you want to do is not to use window.onload to bind events. That is because this can only be run once, and if you have other window.onload statements on your page, you will risk overwriting them. Use .addEventListener instead. So, what we can do is store all the events you want to listen to in an array, and bind them iteratively using IIFE.
In each of these event callbacks, you want to clear both global timers, because:
You want to cancel the self-invoking refresh function, and
You want to restart the countdown towards a "user is idle" state
And then you simply restart the idleTimer in the same callback. The idleTimer will simply restart the self-invoking refresh function when it times out:
var idleClientCheck = function() {
// These events will trigger a new countdown
var events = ['load', 'mousemove', 'mousedown', 'click', 'scroll', 'keypress'];
for (var i = 0; i < events.length; i++) {
// Use IIFE to bind correct event on the fly
(function() {
var e = events[i];
window.addEventListener(e, function() {
// When these events are triggered, we cancel refreshTimer and idleTimer
window.clearTimeout(refreshTimer);
window.clearTimeout(idleTimer);
console.log('Refresh timer cancelled by ' + e + ', will restart in ' + idleDuration + 'ms');
// We restart idleTimer
// idleTimer simply fires refresh() when time runs out
idleTimer = window.setTimeout(refresh, idleDuration);
});
})(i);
}
};
idleClientCheck();
Combining all these at once, and you get a functional snippet:
// Global timers
var refreshTimer = null,
idleTimer = null;
// Some settings
var refreshDuration = 5000,
idleDuration = 3000;
// refresh() is simply a method with a self-invoking to mimic window.setInterval
var refresh = function() {
$("body").append("<p>refreshTable every 5 second.</p>");
// Call itself
refreshTimer = window.setTimeout(refresh, refreshDuration);
};
// idleClientCheck() runs its own timer to check for idle client
var idleClientCheck = function() {
// These events will trigger a new countdown
var events = ['load', 'mousemove', 'mousedown', 'click', 'scroll', 'keypress'];
for (var i = 0; i < events.length; i++) {
// Use IIFE to bind correct event on the fly
(function() {
var e = events[i];
window.addEventListener(e, function() {
// When these events are triggered, we cancel refreshTimer and idleTimer
window.clearTimeout(refreshTimer);
window.clearTimeout(idleTimer);
console.log('Refresh timer cancelled by ' + e + ', will restart in ' + idleDuration + 'ms');
// We restart idleTimer
// idleTimer simply fires refresh() when time runs out
idleTimer = window.setTimeout(refresh, idleDuration);
});
})(i);
}
};
idleClientCheck();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
its work for me ..I have checked and you can also check this in "TryitEditor" of W3Schools
<script>
//SUSPEND THIS FUNCTION IF CLIENT IS IDLE
//ENABLE THIS FUNCTION WHEN CLIENT IS ACTIVE
function refreshTable() {
window.clearTimeout(timer);
timer = window.setTimeout(refreshTable, 5000);
$("body").append("<p>refreshTable every 5 seconds.</p>");
}
var timer = window.setTimeout(refreshTable, 0);
function idleClientCheck() {
var t1;
var t2;
window.onload = resetTimer;
window.onmousemove = resetTimer;
window.onmousedown = resetTimer;
window.onclick = resetTimer;
window.onscroll = resetTimer;
window.onkeypress = resetTimer;
function isNotIdle() {
timer = window.setTimeout(refreshTable, 5000);
//setTimeout(timer);
//alert('isNotIdle');
$("body").append("<p>isNotIdle</p>");
}
function isIdle() {
clearTimeout(t1);
//timer = null;
window.clearTimeout(timer);
timer = null;
$("body").append("<p>isIdle</p>");
//alert('isIdle');
}
function resetTimer() {
clearTimeout(t1);
clearTimeout(t2);
t1 = setInterval(isNotIdle, 9999);
t2 = setInterval(isIdle, 15000);
}
}
idleClientCheck();
</script>

What is the better way to get mouse hold time?

I'm trying to count the time that player is holding the mouse button down. I tried this but it didn't works:
var Game = cc.Layer.extend({
count: false,
countTimer: null,
init: function () {
var selfPointer = this;
this.canvas.addEventListener('mousedown', function(evt) {
selfPointer.count = true;
selfPointer.countTimer = window.setTimeout(selfPointer.Count(), 1);
});
this.canvas.addEventListener('mouseup', function(evt) {
selfPointer.count= false;
window.clearTimeout(selfPointer.countTimer);
});
},
Count: function() {
if (this.count)
{
window.setTimeout(this.Count(), 1);
}
}
This is a part of my code(for brevity) that I want to do an action any 1 milisecond if player is holding the button.
This isn't working besides, I presume that is a better way to do this than mine way. Any ideas?
Why do you use timeouts for this simple task? You can just get time of mousedown, time of mouseup and calculate difference of them. Anyway, timer resolution in browsers is less than 1ms. Read this article of Nickolas Zakas to get more info about time resolution.
Code is:
var Game = cc.Layer.extend({
init: function () {
var holdStart = null,
holdTime = null;
this.canvas.addEventListener('mousedown', function(evt) {
holdStart = Date.now()
});
this.canvas.addEventListener('mouseup', function(evt) {
holdTime = Date.now() - holdStart;
// now in holdTime you have time in milliseconds
});
}
Well if you are targeting newer browsers that are HTML5 compatible you can use web workers for this kind of task. Simply post a message to the web worker on mouse press to start the timer. The web worker can post a message back every 1 ms ish to trigger your in game action and then on mouse release, post another message to the web worker telling it to stop.
Here is just a quick example of how that would work. You would need to run from a local server to have web workers working.
Game.js
function start() {
var worker = new Worker("ActionTrigger.js");
worker.addEventListener('message', function(objEvent) {
console.log("Holding");
});
worker.postMessage("start");
window.onmousedown = function() {
console.log("Mouse press");
worker.postMessage("startTrigger");
}
window.onmouseup = function() {
console.log("Mouse release");
worker.postMessage("endTrigger");
}
}
ActionTrigger.js
var trigger = false;
var interval = 1;
self.addEventListener('message', function(objEvent) {
if(objEvent.data == 'startTrigger')
trigger = true;
else if(objEvent.data == 'endTrigger')
trigger = false;
else if(objEvent.data == 'start')
timerCountdown();
});
function timerCountdown() {
if(trigger)
postMessage("");
setTimeout(timerCountdown,interval);
}
You could use something like this:
http://jsfiddle.net/yE8sh/
//Register interval handle
var timer;
$(document).mousedown(function(){
//Starts interval. Run once every 1 millisecond
timer=self.setInterval(add,1);
});
$(document).mouseup(function(){
//Clears interval on mouseup
timer=window.clearInterval(timer);
});
function add(){
//The function to run
$("body").append("a");
}

Implement a timer into js function

I have already this function I'm trying to add a timer like this: when value >= 1 and user doesn't move mouse for 1 minute or 60 seconds timer starts and redirect user to a new page but if user moves mouse before 60 seconds end the timer resets again.
function pagar(){
var textarea = document.getElementById ("textarea");
/*if (event.propertyName.toLowerCase () == "value") {
alert ("NUEVO VALOR EN EL CAMPO TOTAL: " + event.srcElement.value);
}*/
if (event.srcElement.value>=1)
{
var bottomMenu = $("#main_footer").bottomMenu([
{name:"backward","class":"red", text:getStr("menu_backward")},
{name:"menu","class":"green", text:getStr("menu_menu"), func:function(){parent.location = "./index.html";}, enabled:false},
{name:"forward","class":"green", text:getStr("menu_pay"), func:forward, enabled:true}
]);
}
else
{
var bottomMenu = $("#main_footer").bottomMenu([
{name:"backward","class":"red", text:getStr("menu_backward")},
{name:"menu","class":"green", text:getStr("menu_menu"), func:function() {parent.location = "./index.html";}, enabled:true},
{name:"forward","class":"green", text:getStr("menu_pay"), func:forward, enabled:false}
]);
}
}
I want to add a timer after this:
if (event.srcElement.value>=1)
{
You'll want to attach a mousemove event listener to the window which clears and resets a timer upon movement.
function MouseMoveTimeout() {
// Whatever you want the timeout to do
}
var TimerID;
function InstallMouseMoveTimeout(Install) {
var Timeout = 60000;
var MouseMoveDetector = function(e) {
clearTimeout(TimerID);
TimerID = setTimeout(MouseMoveTimeout, Timeout);
}
if(Install && TimerID == undefined) {
TimerID = setTimeout(MouseMoveTimeout, Timeout);
window.addEventListener('mousemove', MouseMoveDetector, true);
} else {
clearTimeout(TimerID);
window.removeEventListener('mousemove', MouseMoveDetector, true);
TimerID = undefined;
}
}
To use this in your code you would:
if (event.srcElement.value>=1) {
InstallMouseMoveTimeout(true); // Install mouse move timeout
...
} else {
InstallMouseMoveTimeout(false); // Cancel mouse move timeout
...
}
var idleTimer = null; // do this in the global scope
// do the following at the location where you want to reset the timer:
if(idleTimer) window.clearTimeout(idleTimer);
idleTimer = window.setTimeout(function() {
location.href = 'other-site';
}, 60000);
So whenever the second block of code is called the old timer is reset and a new one is started. However, since mousemove events trigger very often, this might screw up performance. In this case create an interval (setInterval()) which triggers e.g. every 10 seconds and only set the current date in your mousemove handler. Then you can simply check in your timer callback if enough time since the last mousemove has exceeded and in this case execute an action.
Sounds like a crazy UI idea! But if you want to do that, you need to declare this somewhere:
var timer;
When you want to start the timer running, do this:
timer = setTimeout(function() { timer = -1; doStuff(); }, seconds * 1000);
That will call doStuff after seconds has elapsed.
If you want to cancel the timer:
if (timer != -1) {
clearTimeout(timer);
timer = -1;
}
By combining these appropriately, you can solve your problem.

Categories