How To Wait For A Function, Which Calls Itself Recursively With Settimeout, To Complete?
I am new to Javascript and currently working on a website, that changes how it looks by itself over time. One part of this page is a 'Typewriter', that writes out a text letter by
Solution 1:
You can wrap the setTimeout
in a promise. This will allow you to use the async/await
syntax to express the intention of your code more clearly, almost as if it was running synchronously.
asyncfunctionrunThis() {
var line1 = document.getElementById("line1");
awaittypeWriter(line1, "papupa");
document.body.style.backgroundColor = "blue";
}
asyncfunctiontypeWriter(element, txt) {
for (var i = 0; i < txt.length; i++) {
element.textContent += txt[i]; // this is shorthand for txt.charAt(i)awaitpause();
}
}
functionpause() {
returnnewPromise(function(resolve, reject) {
setTimeout(resolve, 150);
});
}
Solution 2:
You can pass the function to run at the end as another parameter.
functiontypeWriter(element, txt, callback) {
if (txt.length > 1) {
element.textContent += txt.charAt(0);
var newText = txt.slice(1,txt.length);
setTimeout(typeWriter, 150 , element, newText, cb);
} else {
element.textContent += txt.charAt(0);
callback();
}
}
typeWriter(el, "ABCDEF", runthis);
Solution 3:
You're creating more than one promises and only resolving the last one. You could define the recursive function as an inner function, here is an example:
functiontypeWriter(element, text) {
returnnewPromise (function(resolve,reject) {
functionrecursion(txt) {
element.textContent += txt.charAt(0);
if (txt.length > 1) {
var newText = txt.slice(1, txt.length);
setTimeout(recursion, 150, newText);
} else {
resolve();
}
}
recursion(text);
});
}
Post a Comment for "How To Wait For A Function, Which Calls Itself Recursively With Settimeout, To Complete?"