'How can I run or pause type writer function using pure javascript
I hope someone can throw me a life jacket, I have a text writer function that works like a charm, but I need to add it an extra functionality, that is pause and stop the execution, I can start the ejecution using a button but I don't know how can I pause and play from paused, and also notice the console give an error when I push the button for second time, Sorry I'm novice in JS, I hope was clear with the explanation. This what I have until now.
const playPauseButton = document.getElementById('button-play-pause');
playPauseButton.addEventListener('click', () => {
typewriter();
});
////////////////////////////////
var aText = new Array(
"sint commodi repudiandae consequuntur","m debitis quas aliquid. Reprehend"
);
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 5; // start scrolling up at this many lines
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row
function typewriter() {
sContents = ' ';
iRow = Math.max(0, iIndex-iScrollAt);
var destination = document.getElementById("typedtext");
while ( iRow < iIndex ) {
sContents += aText[iRow++] + '<br />';
}
destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "|";
if ( iTextPos++ == iArrLength ) {
iTextPos = 0;
iIndex++;
if ( iIndex != aText.length ) {
iArrLength = aText[iIndex].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", iSpeed);
}
}
.control-text-writer{
background-color: rgba(0,0,0,0.2);
position:absolute;
display: block;
left:10px;
bottom:20px;
border-radius: 100%;
padding: 0.1rem;
}
.control-text-writer:not(.playing) .control-pause,
.control.playing .control-play {
display: none;
}
<div id="typedtext"></div>
<button id="button-play-pause" class="control-text-writer">
<span class="control-play">
<span>Play</span>
</span>
<span class="control-pause">
<span>Pause</span>
</span>
</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
