Press the button after 60 seconds of inactivity in JavaScript

After a lengthy search and multiple failed attempts with different files, I am in need of the following script:

If there is no interaction with a webpage for 1 minute, the script should automatically: - Click on a button. - Repeat the click every 30 seconds if there is still no interaction.

However, as soon as I start interacting with the webpage again, I want the script to stop running until I'm not interacting anymore.

I've managed to create this script:

function findButtonbyTextContent(text) {
var buttons = document.getElementsByTagName('button');
for (var i=0; i<buttons.length; i++) {
if (buttons[i].firstChild.nodeValue == text)
  return buttons[i];
}
}

function refresh(tijd){
setInterval(findButtonbyTextContent("Refresh").click(), tijd);
}

document.onmousemove = (function() {
var onmousestop = function() {
        refresh(30000);
    }, thread;

return function() {
    clearTimeout(thread);
    thread = setTimeout(onmousestop, 60000);
};
})();

Answer №1

My approach to this problem

let counter, interval, button = document.getElementById('button');

document.onmousemove = function () {
    clearTimeout(counter);
    clearInterval(interval);
    counter = setTimeout(function() {
        interval = setInterval(function() {
            button.click();
        }, 30000);
    }, 60000);
}

FIDDLE

In the provided Fiddle, I assigned an ID to the button and adjusted the time intervals for faster testing.

Additionally, I noticed some issues in your code, like this part:

setInterval(findButtonbyTextContent("Refresh").click(), tijd);

This immediately triggers the click function and returns undefined, not achieving the intended functionality. Also, you are not storing a reference to the interval correctly, leading to it running indefinitely even after clearing the initial timeout.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The code snippets in the Vue3 documentation are quite peculiar

As I peruse the Vue 3 documentation, I notice a recurring pattern in how example code is presented for components: Vue.createApp({}) However, my experience with Vue 3 has been different. Instead of the above syntax, I simply use: <script> export d ...

Green and red values hovering within the keyframe

Currently, I'm facing a dilemma involving keyframes. I have a table populated with values retrieved from a JSON fetch and need to implement a hover effect where values less than 5 show in red, while those equal to or greater than 5 appear in green. Be ...

The issues of cross-origin domains arise when utilizing iframes with src links originating from the server side

Encountering a cross-origin domain issue, receiving the following error while working with an iframe: candidateInterviewCtrl.js:39 Uncaught SecurityError: Blocked a frame with origin "http://localhost:9000" from accessing a frame with origin "http://local ...

I'm curious about the process by which custom hooks retrieve data and the detailed pathway that custom hooks follow

//using Input HOOK I am curious to understand how this custom hook operates. import { useState } from "react"; export default initialValue => { const [value, setValue] = useState(initialValue); return { value, onChange: event =&g ...

JavaScript scripts are not functioning properly in a partial view following a refresh

Issue: The partial view contains JavaScript scripts that work when first loaded, but stop working after being loaded a second time. Description: I have a partial view reloading on value change in a select box (which calls this function). @(Html .DevE ...

Unable to add MySQL results to the array

This is the code I am working on: var nbu = req.body.nbu; var inv=[]; db.query( "SELECT * FROM `invoice_ska` WHERE nm_client =?", nbu, (err, results) => { if (err) throw err; inv.push(results); } ); console.log(inv);//this just [] }); I ...

Error: Unable to access the toISOString property of an undefined object

https://i.sstatic.net/jtZnQ.png import './ExpenseItem.css'; function ExpenseItem(props){ return ( <div className="expense-item"> <div>{props.date.toISOString()}</div> <div className="expen ...

Preserve multiple selected values post form submission using PHP, HTML, and JavaScript

How can I retain the selected values in a form after it is submitted? My current code functions correctly when only one value is selected, but does not maintain all selected values when multiple are chosen simultaneously. Any assistance would be apprecia ...

Console Error: Attempting to set the 'className' property of null object results in an

I'm experiencing difficulties setting up the code. The function should display all songs by a specific artist when their name is entered and the button is pressed. JavaScript file: /** * Utilizes AJAX to request data about artists from an online sou ...

Express Route will respond with a status code of 500 and a generic error message when a file is sent as 'multipart/form-data'

ISSUE DETAILS: I've implemented an express route that accepts files in multipart/formdata format and uploads them to an S3 bucket. To filter image types and temporarily store them on the server, I'm using multer and creating an upload directory. ...

Assign the input text field's value programmatically in the code-behind of a C# Asp.net application

I am attempting to change the value of an HTML input field from C# code behind. These inputs are created through a JavaScript loop, so I have not had much success using run at server or assigning values through <%= %>. Below is my script: var mytab ...

What is preventing me from utilizing automatic reloading in Next.js to view changes without the need to restart the server?

Being a beginner in Next.js and the world of web development, I may have some basic questions. Following the installation guide, I managed to successfully create my first Next.js app. However, I'm facing an issue with auto-reloading when I make change ...

Using Vue to dynamically wrap a component with a tag

Have you ever wondered how the v-if directive in Vue.js can hide an entire component along with its content based on a condition? I am curious to know: Is it possible to only hide the surrounding tag or component without removing its contents? ...

Mapping an array with array objects - a guide to connecting and iterating through

I am working with two arrays: ['x', 'y', 'z'] And array 2: [{ x: 5, y: 10, z: 15, w: 20 }] Is there a way to merge these two arrays to get the following output: [{x: 5, y: 10: z: 15}] I only want the items present in the fi ...

Filtering data from nested arrays in MongoDB

My data structure and schema are as follows: { date: 0, darwin: [ { d: ['string1', 1, 0, 0, 0] }, { d: ['string2', 1, 0, 0, 0] }, { d: ['string3', 1, 0, 0, 0] } ] } I'm try ...

Struggling to get Ajax to function on IE8 with dropdowns, while other browsers are working perfectly fine

My AJAX code functions properly in most browsers, however, it is not performing well in IE. While it successfully creates an XMLHTTPRequest object, the data retrieved from my PHP script is only returning an empty list! Check out my JavaScript code: < ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

Alert: Jade has detected an unforeseen block called "scripts"

I created a jade file with the following content: extends layout block content h1= title p Hello and welcome to #{title} block scripts script(src='/socket.io/socket.io.js') script(src='/javascripts/client.js') But when I try ...

Tracking and monitoring the advancement of multiple ajax post requests

Currently, I am utilizing jQuery for multiple ajax POST requests. In order to effectively manage the success or failure of each request and track the overall progress of the entire batch, my goal is to update the UI with a progress bar and information on t ...

Creating a function that assigns an anonymous function which in turn returns another anonymous function

Can you explain the difference in JavaScript between these two code snippets? var reader = new FileReader(); reader.onload = (function (theFile) { return function (e) { loadData(e.target.result); }; })(file); reader.readAsText(file); a ...