0

I can't understand what I am doing wrong when trying to get these two functions to run in correct order. For some reason my modal window won't show until after the long running ajax call is completed. I went through some other posts talking about using a promise instead to block until it returns. Its turning into a house fire.

function modalShow() { //all it is doing is showing a div...
    var deferred = $.Deferred();
    var show = function () {
        if (!$("#myModal").is(":visible"))
        {
            console.log("showing modal");
            $("#myModal").show();
            setTimeout(show,500); 
        } else {
            console.log("marking deferred");
            deferred.resolve(true);
        }
    }
    show();
    return deferred.promise();
}

function saveData(id) {
    var promise = modalShow();
    promise.then(function () {
        console.log("continuing");
        'super long ajax call
         });
    setTimeout(saveData(id),500);
}  

What I keep ending up with is first no modal popup of any kind even though i run the showModal() on its own and works fine and a never ending loop of

marking deferred
continuing
 marking deferred
continuing
marking deferred
 continuing
 marking deferred
 continuing
marking deferred

Any ideas what I am doing wrong? Looked at a fair number of examples and don't see what I am missing. thanks

macm
  • 544
  • 7
  • 21
  • 2
    you are running saveData(id) in a recursive loop. you are not sending a callback function to setTimeout. – progysm Aug 10 '17 at 19:05
  • Hi. Thanks that solved my 9000 calls in 10 seconds issue. updated my calling function to setTimeout(function () { saveData(id); }, 2000); and that created the correct functionality... sadly I still have no modal popup which is really weird. If the function runs fine on its own from dev tools ... is there a reason it would not run from another function? – macm Aug 10 '17 at 19:16
  • Not sure what you are doing with the HTML, but it shows with a simple div: https://jsfiddle.net/4n6hoyhr/ – progysm Aug 10 '17 at 19:49
  • I think the issue was that it was losing focus in the dom when i was referencing like above... I changed the code to var modal = $("#myModal); and then just referred to the rest as if(!(modal.is(":visible")) etc etc... that seemed to work right away. Thanks for your help though.. it cleared up some confusion. – macm Aug 10 '17 at 20:01

0 Answers0