Hack #41. Refresh Pages Automatically

Reload selected pages every 20 minutes.

Although it's not generally considered "friendly" behavior, there are several reasons why you might want to have some pages refresh themselves automatically. One is simply to keep an eye on the latest news. Another is to keep your login sessions alive longer, on sites that log you out after a period of inactivity.

Greasemonkey allows a lot of freedom, and many user scripts abuse it and behave badly. I recommend moderation and common sense when creating additional load on other people's web servers. A delay of 20 minutes seems reasonable, so that's the default I used for this script.

The Code

This is one of the simplest user scripts you can imagine. When it executes, it sets a timer to call a function after a delay. The function in this case is document.location.reload, which reloads the page.

Tip

Technically, timers are not threads; they simply interrupt whatever is executing at the time. But they are the closest thing to multithreading in JavaScript. You will see setTimeout and its cousin setInterval in many scripts that animate the user interface.

The multiplying factor, 60*1000, converts the timeout delay from minutes to milliseconds, as required by the setTimeout function.

Tip

Although it's ignored in this script, setTimeout has a return value: the ID for the timer that was set. With this ID, it is possible to cancel the timer by calling clearTimeout.

Save the following user script as autoreload.user.js ...

Get Greasemonkey Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.