As part of the JavaScript chapter for our upcoming book Building Web Apps with WordPress, I got a chance to research and work with the Heartbeat API that is new to WordPress 3.6.

It’s a cool little piece of functionality that will help out developers building asynchronous apps on top of WordPress.

At first, I didn’t see the need for it. (It’s not too hard for developers to create their own script to poll the server every few seconds.) But I soon realized why an API like this would be useful. If  you have 5 different plugins all with their own server polling, you are going to have 5 different hits to your server every 15 seconds. However, if they all piggyback on the Heartbeat API, those polling requests are going to be bundled so you are only hitting your server 1 time every 15 seconds. There are other benefits, but that’s the big one to me.

For people trying to get started with the Heartbeat API, I put together this nice little minimal example that you can use as a starting point. The script below simply sends the message “marco” from the client and then detects this on the server and sends back “polo”. The messages are logged in the JavaScript console (so if you inspect elements and click on the console tab in Chrome you will see them). You should be able to easily tweak this to send requests like “how many members are logged in?” and send back a number, etc.

Let me know if you have any questions about the API and I’ll try to address them.