Reputation: 85
new to JS here and was wondering if someone could guide me on how I can pause and delete when implementing a typewriter effect in JavaScript. I've got a function that successfully types out each word in an array, however I would like it to pause after typing each word and backspace or delete the letters before typing the next one.
//counter
var i = 0;
var index = 0;
var texts = ['Salesforce Consultant', 'Developer', 'Writer'];
var speed = 110;
let letter = '';
let currentText = '';
let delay = 25;
function typeWriter() {
//If counter is less than the # of letters in txt, reset array of words
if (i === texts.length) {
i = 0;
}
//Use count to select text to display
currentText = texts[i];
letter = currentText.slice(0, ++index);
document.querySelector("#demo").textContent = letter;
//If letters displayed are the same number of letters in the current text
if (letter.length === currentText.length) {
//Pause before deleting
//Delete letters in word
//Word is done displaying, and reset letters on screen
i++;
index = 0;
}
setTimeout(typeWriter, speed);
}
typeWriter();
<div id="demo"></div>
HTML
<div class="centered">
<div class="intro">
<p>A  </p>
<p class ="typing" id="demo"></p>
</div>
</div>
Upvotes: 0
Views: 1681
Reputation: 350252
You can do this by introducing a variable that determines how the index
will change (+1 or -1). The different delay is just a different argument to setTimeout
.
I would also suggest converting some global variables into function parameters: that way they are better (more narrowly) scoped. The change that these variables get, can be managed by what you let setTimeout
pass on to the next call.
Here is how that could work:
const texts = ['Salesforce Consultant', 'Developer', 'Writer'];
const speed = 110;
const pause = 800; // <--- the longer delay between text direction changes
function typeWriter(i=0, index=1, direction=1) {
let displayed = texts[i].slice(0, index);
document.querySelector("#demo").textContent = displayed;
if (displayed.length >= texts[i].length) { // start removing after pause
setTimeout(() => typeWriter(i, index-1, -1), pause);
} else if (displayed.length === 0) { // go to next text after pause
setTimeout(() => typeWriter((i+1) % texts.length), pause);
} else { // continue in the current direction
setTimeout(() => typeWriter(i, index+direction, direction), speed);
}
}
typeWriter();
<div id="demo"></div>
Upvotes: 3