The Heartbeat API: Changing the Pulse

In the first part of this series we looked at the basics of the Heartbeat API, and how it can be implemented in a plugin. In this tutorial we'll be looking at how you can change the "pulse" of the Heartbeat.

By default the WordPress heart beats once every 15 seconds. You can lower that rate to anything down to one beat every minute. Alternatively you can temporarily increase the rate to one beat every 5 seconds – but only temporarily for two and half minutes before it is reset to the the 'standard' beat: "4 BPM".


Change the Default Pulse

To change the default pulse you can use the wp_heartbeat_filter filter which filters the initial settings of the Heartbeat API. This filter does not allow to you initially set the pulse to 'fast': instead you can only specify a number between 15 and 60 (interval between beats in seconds).


Turn Off Auto-Start

Although requests are only sent to the server when there is data to send, Hearbeat starts running automatically when the page loads. You can turn auto-start off from the default Heartbeat settings:

Switching from server-side to the browser, Heartbeat will then only start running if:

is called. You can also turn off Heartbeat client-side too:


Change the Pulse Client-Side

As well as turning Heartbeat on and off, you can manipulate the beat of the pulse (for example) in response to certain events triggered by the user. For instance, you may listen for when the user starts an activity that requires more regular communication with the server – and so temporarily increase the rate.

From within your JavaScript script:

Warning: Although 'fast' only lasts two and half minutes, if you are continually setting the pulse to 'fast' then, in effect, it permanently runs at that rate. You should be careful about how you change the pulse and do so only when you need to do so.

Change the Pulse Server-Side

As well as changing the pulse browser-side, we can also do this each time the browser communicates with the server. This is done by setting 'heartbeat_interval' in the response – it can be one of 'fast', 'slow' or 'standard'.


User Inactivity

The Heartbeat API also adjusts the beat according to a user's activity. WordPress checks user activity every 30 seconds, if after 5 minutes, there's been no keyboard or mouse activity, the beat is reduced to one beat every hundred seconds. This is done regardless of what it may have been set to by a plugin.

In the final part of this series we'll create a simple working example of a plugin using the new Heartbeat API. We'll create a plugin which gives users 'live' updates on when users log in and out of WordPress.

Tags:

Comments

Related Articles