I want to do something like this for streamlabs alerts (when you have a new subscriber and stuff): https://codepen.io/alticreation/pen/ZYdopE
At first what it does is it grabs an element from the DOM and changes the string to a random string. That makes it good. Then, after half a second, it changes the random string to the final string and I want the process to be seen as in the example. In the console it is also seen that the process follows it well, but it does it all at once.
I've also tried with setInterval, but I haven't been able to get it to work either.
window.onload
var domElement = document.getElementById("alert-message");
var texto = domElement.innerHTML;
var falso = ""
var longitud = String(texto).length;
var caracteres = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZabccdefghijklmnñopqrstuwxyz0123456789-+*/|}{[]~\\\":;?/.><=+-_)(*&^%$#@!)}";
for(var i = 0; i < longitud; i++){
falso += caracteres.charAt(Math.floor(Math.random() * 101));
}
falso = String(falso);
domElement.innerHTML = falso
function cambiar(){
for(i = 0; i < longitud + 1; i++){
domElement.innerHTML = falso
setDelay(i);
}
};
cambiar();
function setDelay(i) {
setTimeout(function(){
falso = texto.substr(0,i) + falso.substr(i);
console.log(falso);
domElement.innerHTML = falso
}, 2000);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id= "alert-message">Pepe nos está siguiendo</div>
<script src="src/prueba.js"></script>
</body>
</html>
When the return function is anonymous or you include parentheses, it is executed immediately, without waiting.
I don't know how to do it with anonymous function, but here is a solution: You must create a function to be executed and include it as the first parameter without parentheses, for this case, it is enough with the change function and recursive calls until the chain is completed.