Skip to content Skip to sidebar Skip to footer

Pause Javascript Function

I need to pause a JavaScript function execution in the middle and then resume it after a button click. Please help me.

Solution 1:

This isn't possible.

Break the function up in to two parts, run one, and have the other assigned to the click event handler of the button.

Solution 2:

You could use a pop up box.

alert("Pausing to get Coffee");

Solution 3:

Like David said, it is not possible to stop execution of a function in Javascript (well, not at the moment anyway). One solution would be this :

** EDITED ** after you added some precision to what you wanted to do

// pass the reference of the button id to the functionfunctionshowConfirm(message, callback) {
   // 1. check if the lightbox is not already created, if not create it// 2. keep a reference to your key elements, for example, your buttonsvar btnOk = document.getElementById('btnOk');  // ...for examplevar btnCancel = document.getElementById('btnCancel');  // ...for example// 3. have a 'cleanup' function so you can dismiss your lightbox, unregister//      any events/callbacks, etc.var cleanup = function() {
      // 6. hide lightbox// 7. remove events/callbacks, etc.
      btnOk.click = null;  // for example
      btnCancel.click = null; // for example// etc.
   };


   // 4. update your lightbox with the message given in argument// 5. register some events to your buttons...
   btnOk.click = function() {
      callback(true);  // ok was pressedcleanup();
   };
   btnCancel.click = function() {
      callback(false); // cancel was pressedcleanup();
   }

}

All you have to remember is that, in Javascript, everything should be asynchronous. If your function should return a value, it should be a function that does not require long to execute. As soon as you read "user input" with Javascript, you need callbacks. You might want to take a look at how other lightbox implementations are done, especially in frameworks like JQuery, etc.

Post a Comment for "Pause Javascript Function"