First of all, I understand pre-optimization is the root of all evil (and I have a nasty tendency of falling into that trap). However, I feel I must think this through, because the implications of taking a wrong approach can result in a lengthy rewrite of the code.
How can I reliably track a visitor's time spent listening to music through the page's audio player?
I'm using jPlayer on my website to serve audio content. I want to reward my users with points for listening:
- Every full minute spent listening rewards a point.
- No points are rewarded for fractions of a minute.
- Audio files are usually between 30 minutes and 2 hours long. Users can start and stop playback at any time, and scrub through the file as they please.
I have no experience with timing sensitive activity tracking. I'm not aware of any best practices for something like this. Does anyone have experience with this sort of visitor tracking?
I've come up with two potential solutions, but before programming all of that, I need advice on which one to pursue and why.
Method 1: Save start and stop events
- When the
$.jPlayer.event.play
event is triggered, insert a record in database with start time. - When the
$.jPlayer.event.pause
or$.jPlayer.event.ended
events are triggered, calculate amount of minutes between saved start-time record and the current time. - To prevent users from hammering the database, JavaScript would wait for 60 seconds before inserting the record in database.
Pro
Database traffic is kept to a minimum: one insert and one delete from the table for each consecutive playback longer than 1 minute.
Con
There is a high chance a users will not be rewarded anything if they don't pause playback before leaving the site, closing the tab or closing the browser. Between the start and stop events no other tracking occurs so their generated reward is completely lost.
Method 2: Periodic saving of progress
- When the
$.jPlayer.event.play
event is triggered, save a timestamp client-side and start a loop. This loop could interval as often as once a minute. - At each interval, update the user's points in the database with the appropriate reward.
- When the
$.jPlayer.event.pause
or$.jPlayer.event.ended
events are triggered, break the loop and clear the timestamp.
Pro
With an interval of 1 minute, the most a user would miss out on in case they navigate away from the site, close the tab or close the browser, is a single point. That's a lot better than losing all progress made using Method 1.
Con
With a high traffic website and many users playing music simultaneously, could it put too much strain on the database?