⏲ How to Calculate Estimated Reading Time with Contentlayer
Add reating time as computed field
To calculate the reading time with contentlayer you can use the computedFields
in your DocumentType
.
Create the calculateReadingTime function
-
Define the function: First, define a function that will calculate the estimated reading time. You can name the function anything you like, but for the purposes of this guide, we'll call it
calculateReadingTime
. -
Determine the average reading speed: The estimated reading time will depend on the average reading speed of your audience. According to research, the average adult reads at a speed of about 200-250 words per minute. can use this value as a baseline for your calculations.
-
Calculate the word count: Before you can calculate the estimated reading time, you need to determine the word count of the text that you want to analyze. You can do this using the JavaScript "split" method, which will split the text into an array of words, and then use the "length" property to count the number of words.
-
Calculate the estimated reading time: Once you have the word count and the average reading speed, you can calculate the estimated reading time by dividing the word count by the reading speed. This will give you the estimated reading time in minutes.
-
Format the output: Finally, you can format the output to display the estimated reading time in a user-friendly way. You might choose to round the estimated reading time to the nearest minute, or display it as a range (e.g. "2-3 minutes").
Display the reading time on your website
Now you can display the reading time on your website by using the readTime
field.