Modal Dialogs in Loops

There is no command in JavaScript that allows you to tell JavaScript to wait for the modal dialog to complete before continuing to run your process and so you need to split your code in two at the point where you want to insert a modal dialog - calling the modal dialog as the last statement of the first function and hiding it again as the first statement in the second function (or just calling the hide function by itself if the dialog is the last statement in your original function. Even with splitting the code like that there will be nothing to stop any code from outside of your split function from running if the function you need to split is called from another function. Where that is the case the first of your split functions will still return to the function that called it to allow that code to continue running while your dialog is displayed and only the code inside your second function will be delayed until a button is pressed.

This limitation also means that a rewrite of your code is required if you want to insert a modal dialog into the middle of a function. The more complex situation which requires the more major rewrite is where you want the modal dialog in the middle of a loop as then you need to rewrite the code in a way that removes the loop from around the dialog and instead set up a function that can process one pass through the loop calling your dialog at the end which then in turn calls the same function again which can test at the appropriate spot whether it should exit to whatever processing is supposed to happen next.

Let's take a look at how we would need to rewrite a function if we want to insert a modal dialog into the middle of a loop. So if we have a function that we want to have run as if it reads:

testfunc = function() {
   var i;
   // some statements 1
   for (i = 0; i < 10; i++) {
      // some statements 2
      modal();
      // some statements 3;
   }
   // some statements 4;
}

We will need to rewrite it as two functions like this with modal() calling func1() when the button is pressed to end the dialog and continue the processing from where it is currently up to:

 testfunc = function() {
   var i, s, func1;
   s = 0;
   func1 = function() {
      if (1 === s) {
         // some statements 3
         i++;
      }
      if (i < 10) {
         // some statements 2
         s = 1;
         modal();
// calls func1 to continue
      } else {
         // some statements 4;
      }
   }
   // some statements 1
   i = 1;
   func1();
}

As you can see, a rewrite of the code to insert a modal dialog into the middle of a loop is possible.

The situation where no loop is involved is not such a complex change and in fact it is possible to get JavaScript to rewrite the code for you when all your modal dialog calls are not inside loops and just need to create a pause in sequential code.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate