jake9115
jake9115

Reputation: 4084

How can I have JavaScript output messages prior to completing a function execution?

I have a webpage built with Flask serving my python code and a template / webpage with HTML and JavaScript. I have a simple webpage currently that has a button. When the user clicks the button, it calls a JavaScript function. The function performs several tasks that take some time. A text area is updated during the function execution with updates about what is happening. Then the function finishes execution.

However, those messages within the JavaScript function only are displayed simultaneously once the function has completely finished executing. That is, I cannot update any HTML objects on my page until the Javascript function finishes. How can I update an HTML object in real-time so the user can get info about what is happening as this longer function executes?

Some example code. My index.html looks something like this:

script type="text/javascript">
function executeCode() {
     document.getElementById("outputLog").innerHTML += "<br>Beginning the function";
     ** do some time consuming stuff **
     document.getElementById("outputLog").innerHTML += "<br>Almost done";
     ** do some more stuff **
     document.getElementById("outputLog").innerHTML += "<br>Done!";
}

...

<button onclick="executeCode()">Press Me!</button>
<p id="outputLog"></p>

However, when the function is called, there is a lag equal to the length of total function execution time, after which all three messages simultaneously appear as a block of text. What do I need to do to allow real-time updates for the user as the function is running?

Upvotes: 1

Views: 48

Answers (1)

Vinod kumar G
Vinod kumar G

Reputation: 655

Use of promise object in javascript.

var promise1 = new Promise(function(resolve, reject) {
  resolve('Success!');
});

promise1.then(function(value) {
  console.log(value);
  // expected output: "Success!"
});

normally use ajaxfunction.then(funciton4success(),funciton4failer()) or you can use var promiseallobj = new promiseAll(ajaxfunction1,ajaxfunction2,...)

promiseallobj.then(successcallbackfunction(),failurecallbackfunction())

for more check link - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

Upvotes: 1

Related Questions