Calculate the estimated reading time of an article using JavaScript

mahabub.devs3
Mahabubur Rahman
Published on Sep, 20 2024 1 min read 0 comments
image

Some sites display an estimated time to read their article. So it will help the user to make a decision, read instantly or save some other time for reading.

Let's see how to calculate the approximate reading time of a article.

 

First I will write a dummy article in the middle of an HTML page.

    function EstimatedReadingTime() {
      const text = document.getElementById("article").innerText;
      const wpm = 200;
      const words = text.trim().split(/\s+/).length;
      console.log(words,wpm)
      const time = Math.ceil(words / wpm);
      document.getElementById("time").innerText = time;
    }
    EstimatedReadingTime();

Then add the page where you want to display the reading time.

<p><span id="time"></span> minute read</p>

Now write the JavaScript function to calculate the reading time.

    function EstimatedReadingTime() {
      const text = document.getElementById("article").innerText;
      const wpm = 200;
      const words = text.trim().split(/\s+/).length;
      console.log(words,wpm)
      const time = Math.ceil(words / wpm);
      document.getElementById("time").innerText = time;
    }
    EstimatedReadingTime();

Let's see what the EstimatedReadTime() function is doing:

  • text - Face all text of the article, so that we can count the words.
  • wpm - Average reading speed of adults (words per minute).
  • word - calculates the total number of words (length) by dividing each space.
  • time - calculates the reading time and converts it to the nearest integer number.

We calculate the time and display it in <span id = "time"> </span>.

After reading this article, now you know how to display the estimated reading time for an article, which can easily be used on a blog or news website.

0 Comments