0

I've a function that, once called, calls another(synchronous) that creates a tab, then waits(asynchronously) two conditions to be true before executing another function(that should load content to the new tab).

I've tried to make the function asynchronous and to find ways to "pause" its execution until the conditions are true.

var onChosenFileToOpen = function(theFileEntry) { 

$('.nav-tabs li:nth-child(' + $(".nav-tabs").children().length + ') a').click(); //synchronous function that creates a tab
var checker=setInterval(()=>{
  if(currentiframe.contentWindow && currentiframe.contentWindow.editor){//waits those 2 conditions to be true
    currentiframe.contentWindow.readFileIntoEditor(theFileEntry)//content is loaded to that tab
    clearInterval(checker)
  }

},1)};

This works fine when someone manually(through clicking a button/menu) executes that function. But if it's called multiple times at once, many tabs are created and only the last one loads the content. I need a way to wait the first call of said function to completly end before running the next ones.

peq42
  • 346
  • 4
  • 18
  • If you could post a working example using the Stackoverflow JS Fiddle feature, it would be a lot easier to debug. – Todd Chaffee Apr 27 '19 at 18:59
  • How about firing an `event` when it is ready? It feels like that would be a lot less hacky – Miroslav Glamuzina Apr 27 '19 at 18:59
  • you can check the event , maybe the event <> and add the function – rapaelec Apr 27 '19 at 19:14
  • Do you need to stick with jQuery for this task? Sounds like a usecase for async/await. Also I would think about using while() loop – mkbctrl Apr 27 '19 at 19:20
  • What you need is a queue (like [this](https://stackoverflow.com/a/18952698/1048572) or [that](https://stackoverflow.com/a/54446941/1048572), or even [using jQuery](https://stackoverflow.com/q/1058158/1048572)) – Bergi Apr 28 '19 at 13:20

1 Answers1

0

I've solved this(after a few hours of try and error and google search) using the following:

Once the main function is called, it pushes the value received to an array and calls another function, that creates one tab, loads content(stored in the array's first positin) to it, shifts the array, then executes itself again in case there are still more values in it.

Code:

var callagain=true;
var tabstocreate=[]
var onChosenFileToOpen = function(theFileEntry) { 
tabstocreate.push(theFileEntry)
    thequeue();


};

function thequeue(){

  if(callagain===true && tabstocreate.length>0){

    $('.nav-tabs li:nth-child(' + $(".nav-tabs").children().length + ') a').click(); 

    var checker=setInterval(()=>{
      if(currentiframe.contentWindow.editor){
        currentiframe.contentWindow.readFileIntoEditor(tabstocreate[0])
        tabstocreate.shift()
        clearInterval(checker)
        callagain=true
        if(tabstocreate.length>0){
          thequeue()
        }

      }

    },1)
    callagain=false
  }


}
peq42
  • 346
  • 4
  • 18