简体   繁体   中英

Code doesn't run in order? Updates to DOM happen all at once?

I'm having a bit of trouble with running my code in order. Basically I have a function that hides an element, console log a message then run another function that makes a slow and massive change to the DOM.

Ideally the hide occurs first to signal the user response has been made, then they can deal with the lag for a few seconds as everything refreshes. But right now, the console gets logged first, then all the changes happen at once after a few seconds. So the hide occurs together with the updates.

If it makes any difference, the update function creates and destroys several div elements, then starts creating JSXGraphs and updating functions, points, etc on those graphs.

check_answer(answer_input) {
  if (this.ans == answer_input) {
    $("#answer-card-section").hide();
    console.log("CORRECT!");

    current_question.update();
    return true;
  }
  else {
    return false;
  }
}

Thanks!

When executing long running functions in JS the calls to render the UI can be blocked. In some cases it can also prevent the previous operation from visibly updating the DOM, which is what you're seeing here.

The simple fix is to put the update() call within a timeout with a short delay. This will allow the hide() to update the DOM first. Try this:

function check_answer(answer_input) {
  if (this.ans == answer_input) {
    $("#answer-card-section").hide();

    setTimeout(function() {
      current_question.update();
    }, 25);
    return true;
  }
  else {
    return false;
  }
}

It seems that you need to execute a callback function after all the hide -operations are finished. One way to achieve this in jQuery is to use $.when().done :

function check_answer(answer_input) {
  if (this.ans == answer_input) {
    $.when( $("#answer-card-section").hide() ).done(function() {
      current_question.update();
    });
    return true;
  } else {
    return false;
  }
}

But beware, in general the return of this function will happen before current_question.update() has been finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM