Note that there are some explanatory texts on larger screens.

plurals
  1. POWait for a recursive jQuery function to completely finish
    text
    copied!<p>Another one that should be simple, but is giving me trouble. I am trying to learn about jQuery's .Deferred() and .promise() functionality to delay certain actions until a recursive function is completely finished. Currently, my code is similar to the following:</p> <pre><code> function showText(setTarget, setMessage, setIndex, setInterval) { var defer = jQuery.Deferred(); var doShowText = function (target, message, index, interval) { if (index &lt; message.length) { $(target).append(message[index++]); setTimeout(function () { doShowText(target, message, index, interval); }, interval); } else { alert("Done!"); defer.resolve(); } }; doShowText(setTarget, setMessage, setIndex, setInterval); return defer.promise(); } function startButtonClick() { displayElement($("#getElement")); showText($("#getElement &gt; h1"), "This text will slowly write to the screen.", 0, 50).promise() .then(alert("Finished.")); } </code></pre> <p>When this runs, "Finished" alert (which I am trying to defer) runs after the first execution of the recursive script, so it will appear when only one letter has been printed (not the intended result). The "Done" alert, however, appears correctly once all of the letters have been printed and the recursion is finished, so it seems as though my defer variable should not be resolved until then. Can anyone help me discover why the "Finished" alert is being called early here? Any assistance is appreciated!</p> <p>EDIT: I realized I had accidentally posted a slightly older version of my code. It has been updated with the correct version (the behavior at run time is the same).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload