Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to get the client timezone offset in JavaScript?
Next article icon

How to Detect Idle Time in JavaScript ?

Last Updated : 24 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The idle time is the time that the user doesn’t interact with a web page. This interaction can be either moving the mouse, clicking on the page, or using the keyboard. This time can be detected to execute certain events that may need to occur after a certain period of idle time. \

Method 1: Using JavaScript: For the implementation, two functions are created, one is the function that resets the timer whenever user interaction is detected and the other is the function that would be executed periodically during the time the user is idle. The reset function consists of the setInterval() function, which is used to create a new interval that will repeatedly invoke another function. The timer created is assigned to a variable that will be used to clear out the old timer whenever this function is called again on user interaction. 

This function is invoked by binding it to the events that cause interaction with the page. These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress. 

The other function which will be invoked when the user is idle can be used to keep track of the time and perform actions when the user has been inactive for a longer time. An example of this would be to log out the user when inactive for more than a specified time. 

Example: 

html




<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to detect idle time in
        JavaScript elegantly?
    </b>
      
    <p>
        The timer will be incremented every
        second to denote the idle time.
        Interaction with the mouse or
        keyboard will reset and hide the timer.
    </p>
      
    <p class="timertext" style="font-size: 1.5rem;">
        You are idle for
        <span class="secs"></span> seconds.
    </p>
      
    <script type="text/javascript">
        let timer, currSeconds = 0;
          
        function resetTimer() {
          
            /* Hide the timer text */
            document.querySelector(".timertext")
                    .style.display = 'none';
          
            /* Clear the previous interval */
            clearInterval(timer);
          
            /* Reset the seconds of the timer */
            currSeconds = 0;
          
            /* Set a new interval */
            timer =
                setInterval(startIdleTimer, 1000);
        }
          
        // Define the events that
        // would reset the timer
        window.onload = resetTimer;
        window.onmousemove = resetTimer;
        window.onmousedown = resetTimer;
        window.ontouchstart = resetTimer;
        window.onclick = resetTimer;
        window.onkeypress = resetTimer;
          
        function startIdleTimer() {
              
            /* Increment the
                timer seconds */
            currSeconds++;
          
            /* Set the timer text
                to the new value */
            document.querySelector(".secs")
                .textContent = currSeconds;
          
            /* Display the timer text */
            document.querySelector(".timertext")
                .style.display = 'block';
        }
    </script>
</body>
 
 

Output:

How to Detect Idle Time in JavaScript ?

How to Detect Idle Time in JavaScript ?

Method 2: Using jQuery: It similar to the above method, however here a new timer is not created every time when user interaction is detected. Instead, the running timer is reset to 0 whenever user interaction is detected. For the implementation, two functions are created, one is the function that resets the timer to 0 whenever user interaction is detected and the other is the function that would be executed periodically during the time the user is idle. A new variable is defined which will globally represent the current time of the idle timer. 

Using the document.ready() event, a timer with the setInterval() function is created which repeatedly invokes another function that handles what will happen when the user is idle for a specified time. The reset function consists of a simple statement that will change the value of the timer variable to 0, effectively resetting the current idle time. This function is invoked by binding it to the events that cause interaction to the page. These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress. 

Example: 

html




<head>
    <script src=
"https://code.jquery.com/jquery-3.4.1.min.js">
    </script>
</head>
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to detect idle time in
        JavaScript elegantly?
    </b>
      
    <p>
        The timer will be incremented every
        second to denote the idle time.
        Interaction with the mouse or keyboard
        will reset and hide the timer.
    </p>
      
    <p class="timertext" style="font-size: 1.5rem;">
        You are idle for
        <span class="secs"></span> seconds.
    </p>
      
    <script type="text/javascript">
        var currSeconds = 0;
          
        $(document).ready(function() {
          
            /* Increment the idle time
                counter every second */
            let idleInterval =
                setInterval(timerIncrement, 1000);
          
            /* Zero the idle timer
                on mouse movement */
            $(this).mousemove(resetTimer);
            $(this).keypress(resetTimer);
        });
          
        function resetTimer() {
          
            /* Hide the timer text */
            document.querySelector(".timertext")
                .style.display = 'none';
              
            currSeconds = 0;
        }
          
        function timerIncrement() {
            currSeconds = currSeconds + 1;
          
            /* Set the timer text to
                the new value */
            document.querySelector(".secs")
                .textContent = currSeconds;
          
            /* Display the timer text */
            document.querySelector(".timertext")
                .style.display = 'block';
        }
    </script>
</body>
 
 

Output:

How to Detect Idle Time in JavaScript ?

How to Detect Idle Time in JavaScript?



Next Article
How to get the client timezone offset in JavaScript?
author
sayantanm19
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to Get Current Time in JavaScript ?
    This article will show you how to get the current time in JavaScript. Whether you are creating a digital clock, scheduling events, or simply logging timestamps, knowing how to retrieve the current time is essential. Here, we will cover different methods to get the current time in JavaScript. Table o
    3 min read
  • How to Set Time Delay in JavaScript?
    Delaying the execution of code is a fundamental technique that is commonly used in JavaScript for tasks like animations, API polling, or managing time intervals between actions. JavaScript provides several built-in methods to set time delays: setTimeout() and setInterval(). We can set time delay in
    2 min read
  • How to Get Milliseconds in JavaScript?
    In JavaScript, you can get the current time in milliseconds, which is useful for timestamping events, measuring time intervals, and performing time calculations. JavaScript provides various methods to precisely measure time down to the millisecond, including Date.now(), performance.now(), and the Da
    2 min read
  • JavaScript - How To Create A Countdown Timer?
    A countdown timer is a timer that runs for a specific time limit and when that limit get crossed then it stops the timer and the message get displayed on the screen. it can be used for a website or blog to display the countdown to any special event, such as a birthday or anniversary. The Basics of a
    4 min read
  • How to get the client timezone offset in JavaScript?
    The client's timezone offset could be detected by using the Date object's getTimezoneOffset() method. The getTimezoneOffset() method returns the time difference between UTC time and local time, that is the time offset, in minutes. This offset is changed by dividing by 60 and negating the result. Not
    1 min read
  • How to Detect Network Speed using JavaScript?
    Network speed detection in JavaScript involves measuring the time it takes to download a known file or resource and calculating the download speed. To calculate the speed of the network a file of known size is chosen from a server to download. The time taken to start and complete the download is rec
    2 min read
  • How to get seconds since epoch in JavaScript?
    Given a date, we have to find the number of seconds since the epoch (i.e. 1 January 1970, 00:00:00 UTC ). The getTime() method in the JavaScript returns the number of milliseconds since January 1, 1970, or epoch. If we divide these milliseconds by 1000 and then integer part will give us the number o
    1 min read
  • How to detect browser or tab closing in JavaScript ?
    Detecting browser or tab closure in JavaScript is essential for preventing data loss or unintended navigation. Using the beforeunload event, developers can prompt users with a confirmation dialog, ensuring they don't accidentally leave a page with unsaved changes or important information. The before
    2 min read
  • JavaScript Date setTime() Function
    The JavaScript Date setTime() Function is a built-in Function in Javascript that is used to get a date object by adding given milliseconds to the date 01/01/1970 Syntax: date.setTime(milliseconds) Parameters: setTime() Function takes parameters as follows. milliseconds: Number of milliseconds to add
    2 min read
  • How to stop setInterval Call in JavaScript ?
    In JavaScript, the setInterval() function is used to repeatedly execute a specified function at a fixed interval. However, there may be scenarios where we need to stop the execution of setInterval() calls dynamically. Stopping a setInterval() call in JavaScript is essential to prevent ongoing repeti
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences