How to Calculate Time to Read an Article in JavaScript
Tags: javascript, webdev, programming
Published: 2023-03-03 08:56:06

Calculating the time it takes to read an article is a useful feature for many websites, especially for those that provide content in the form of articles, blogs, or tutorials. The ability to estimate the time it takes to read an article can help users plan their time better, especially if they have limited time.

In this article, we'll learn how to calculate the time it takes to read an article (or text) in JavaScript using an average reading speed (number of words read per minute).

### How to Get the Article Content

First, we need to create article content with HTML and then use JavaScript to get the text content of the `article` element. For example, in the code block below, there is an article element that holds all details about your content, such as the title in an `<h1>` tag and the content in paragraph elements and other elements, together with a JavaScript file linked using `script` tag:
 

```html
<body>
    <article>
        <h1>Here is the heading</h1>
        <div class="read-time"></div>
       
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum, suscipit, laborum inventore ullam iure ipsam ut, molestiae quam nulla similique amet perspiciatis expedita quod sit nihil eum voluptatibus quibusdam. Dicta?</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum, suscipit, laborum inventore ullam iure ipsam ut, molestiae quam nulla similique amet perspiciatis expedita quod sit nihil eum voluptatibus quibusdam. Dicta?</p>
        
    </article>
    <script src="./main.js"></script>
</body>

```
This is what an actual article looks like when it gets served in a browser. The next step would be to use JavaScript to get the entire article element with any HTML DOM document method like `querySelectorAll`. Create a file called `main.js` in the current folder, and then have this code in it: 

```javascript
let article = document.querySelectorAll('article')
let readTimeDiv = document.querySelector('.read-time')
```
In the code above, we declare a variable called `article` to store all the content from the HTML document. We also declare a constant called `readTimeDiv` to get the container with reference to the class name, which will display the result.
_Note: In a situation where you are fetching your content from an external API. This means you should have it stored in a variable then you can proceed with the next steps._

### How to Calculate the Word Count
Before we can calculate the reading time, we need to get the word count of the content. We can do this by looping through all the content in the `<article>` tag.

```javascript
let numOfWords = 0;
article.forEach(article => {
        numOfWords += article.innerHTML.split(" ").length;
    });
```
In the above code, we first initialize the number of words to `0`, then loop through the paragraph to get the word count by splitting the article text into an array of words using the `split()` method and then getting the length of the resulting array to determine the word count.

### Determining the Reading Speed

The average reading speed for adult English speakers is [around 200-300 words per minute](https://www.sciencedirect.com/science/article/abs/pii/S0749596X19300786#:~:text=Based%20on%20the%20analysis%20of,and%20260%20wpm%20for%20fiction.), but this can vary depending on the individual. To calculate the time it takes to read an article, we'll use an average reading speed of 260 words per minute.

```javascript
const averageWPM = 260;
```

### How to Calculate the Reading Time

To calculate the reading time, we can create a function to handle this task, where we would declare all the variables and then perform the operation.

```javascript
const calculateReadTime = () => {
    let numOfWords = 0;
    const averageWPM = 260;
    article.forEach(article => {
        numOfWords += article.innerHTML.split(" ").length;
    });
    let readTime = Math.ceil(numOfWords / averageWPM);
    return readTimeDiv.innerHTML =  readTime + " " + "minutes read";
}

```
In the code above, we start by defining a function named `calculateReadTime`. We then define a constant, `averageWPM` that holds the average reading speed of 260 words per minute. Next, we calculated the number of words and stored it in the `numOfWords` variable.

Finally, we calculated the reading time by dividing the number of words by the average reading speed and rounding up the result using the `Math.ceil` function.

_Note: The `Math.ceil()` method will round up and return the smaller integer greater than or equal to a given number._

In summary, we are getting the entire article from our HTML page and the total number of words in the article tag. We are then estimating how long it will take a user to read such a number of words based on the general statistics that a human can read an average of 260 words per minute. This is what our final code looks like:

```javascript

var article = document.querySelectorAll('article')
const readTimeDiv = document.querySelector('.read-time')
const calculateReadTime = () => {
    let numOfWords = 0;
    const averageWPM = 260;
    article.forEach(article => {
        numOfWords += article.innerHTML.split(" ").length;
    });


    let readTime = numOfWords / averageWPM
    return readTimeDiv.innerHTML =  Math.ceil(readTime) + " " + "minutes read";
}
calculateReadTime();
```
The result is the estimated time it takes to read the article in minutes. It's important to note that the **estimated** reading time is an estimate and should not be taken as an exact measure of how long it will take a user to read an article because several factors can affect its accuracy, such as distractions while reading, comprehension, and the presence of multimedia content like images and videos.

### Conclusion

In conclusion, calculating the time it takes to read an article can be a valuable tool for online content creators and readers. Using JavaScript and a few simple algorithms, you can easily determine the average reading time of your articles and provide your readers with a more accurate estimate of the time it will take to complete a piece. 

Thanks for reading. Have fun coding!