BLOG // May 5, 2021
Simple plain JavaScript time to read function
Time to read on blog posts is a trending feature and I often see people using heavy, bloated JS to display that. It's actually quite simple to add a quick read time counter to content.
Average reading time
The average reading time is 200 words per minute. You can lower that for very technical content, perhaps to 150 as an example. I've found that to be a great number for a technical blog like mine.
The code
Below is a function you can call with your content to return the number of minutes taken to read the article, in JavaScript.
function timeToRead(content) {
var totalWords = content.trim().split(/\s+/).length;
var timeToRead = totalWords / 200;
var timeInt = Math.ceil(timeToRead);
if (timeInt > 1) {
return timeInt + ' minutes';
}
return timeInt + ' minute';
}
Final words
This can easily be implemented in other languages. Essentially, work out the number of words and divide it by 200, then round it.
Comments
Subscribe to new articles
If you enjoy my content, consider subscribing. You will only receive new blog stories, no other email.