Skip to content Skip to sidebar Skip to footer

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.


async function runThis() {
  var line1 = document.getElementById("line1");
  await typeWriter(line1, "papupa");
  document.body.style.backgroundColor = "blue";
}

async function typeWriter(element, txt) {
  for (var i = 0; i < txt.length; i++) {
    element.textContent += txt[i]; // this is shorthand for txt.charAt(i)
    await pause();
  }
}

function pause() {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, 150);
  });
}


Solution 2:

You can pass the function to run at the end as another parameter.

function typeWriter(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:

function typeWriter(element, text) {
    return new Promise (function(resolve,reject) {
        function recursion(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?"