Michael
Michael

Reputation: 13

javascript click button if inactive for 60 seconds

I've searched for a long long time and made different files which were not working properly.

What i need: If i'm not interacting with a webpage for 1 minute execute the following: - click on button. - repeat click after 30 seconds if i'm still not interacting

When i come back at the webpage (interacting again), i don't want this script to keep running... Only when i'm not interacting again.

I've come to this:

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);
};
})();

Upvotes: 1

Views: 1113

Answers (1)

adeneo
adeneo

Reputation: 318232

Here's how I'd do it

var int, timer, btn = document.getElementById('button');

document.onmousemove = function () {
    clearTimeout(timer);
    clearInterval(int);
    timer = setTimeout(function() {
        int = setInterval(function() {
            btn.click();
        }, 30000);
    }, 60000);
}

FIDDLE

I gave the button an ID and shortened the times in the Fiddle so as to not have to wait for minutes to see the result.

As a sidenote, you're code has some issues, for instance this

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

calls the click function right away and returns undefined, so it doesn't do at all what you think it does, and you're not storing a reference to the interval anywhere, only to the initial setTimeout, and clearing that doesn't clear the interval, it still keeps on going.

Upvotes: 2

Related Questions