How does it work?
Here is the full code:
const text = "My skink is out on the town";
const typedOut = document.querySelector("#typed-out");
let index = 0;
function writeText() {
typedOut.innerText = text.slice(0, index);
index++;
if (index > text.length) {
index = 0;
}
}
setInterval(writeText, 100);
Nothing happens until the last line which runs the function writeText
repeatedly every 100 milliseconds.
The text used is stored in a variable and this creates a new array using the slice
array method (See this page).
The finishing point is the value of the index
variable but the line index++
increases this value by 1 each time the function is run. So although it appears a new letter is being added one by one this is an illusion. What is really happening is the whole of the array is added every 100ms and each time it has one letter more than the previous run through.
The final if
statement checks the length of the array and compares it to the length of the whole text. Once the index
variable is greater than the length of the text it is reset back to zero and the next time round there are no letters to print out.
One hundred milliseconds later and the value of index
is increased to 1
and the array is printed from 0
to 1
, the first letter.
The slice() method
Slice here uses two parameters the starting point and the finishing point.
You can also use a single parameter. If you use the number 1, myVar.slice(1)
you get all the items starting with position 1
. If you use a negative number such as: myVar.slice(-3)
this will grab the last 3 items of the array.
text.slice(0, index);
slice() with sort() and join()
let monkey = ['marmoset', 'gelada', 'linsang', 'talapoin', 'grivet', 'lutung', 'drill', 'mangerbey']
Adding the sort()
method arranges the array alphabetically and join()
allows you to separate each item with a string.
monkey.slice(1, -1).sort().join(', ')