'Animate text letter by letter with requestAnimationFrame()

I would like to animate text from the DOM letter by letter using requestAnimationFrame(). I have achieved it with setInterval() and also with requestAnimationFrame() too, but I still can't achieve it to be played for predefined time. For example, on my machine every frame plays for 6ms, but I would like the whole text to be played for example for 5s. So if I have 100symbols each symbol should be added for 50ms and then the other one. Could you please recommend me a solution? Here is my code:

const text = document.getElementById('text');
const textContent = text.innerText;
text.innerHTML = '';
let i = 0;
let totalTime = 2000;
let start;

function animateText(time) {
    if (start === undefined) {
        start = time;
    }

    if(text.innerHTML.length < textContent.length) {
             requestAnimationFrame(animateText);
             text.innerHTML += textContent[i];
             i++;
    }
}

requestAnimationFrame(animateText);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source