0

I would like to change the HTML of a node, then wait 500ms, then continue my code where it has to change again. like this:

centerDiv.innerHTML = "waiting";
pauseMs(interTrialInterval);
...
centerDiv.innerHTML = "going again"

where pauseMs is as follows:

function pauseMs(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}  

When I execute the code, the 'waiting' doesn't show up, as a matter of fact, digging into it I have the feeling that the HTML gets updated after the pauseMs is completed, and a few lines later in the code gets changed to "going again".

Strange thing: If I debug it and step over the code, it works as it should.

I tried forcing a repaint by adding offsetHeigth, that didn't work.

centerDiv.innerHTML = "waiting";
centerDiv.offsetHeight;

Any help most appreciated, Joris

EDIT: As pointed out by many, this subject has been extensively discussed in this SO question. However one must notice that DOM changes requested before this "busy pause" are NOT executed by the browser until the pause is over.

As suggested I refactored my code using setTimeout.

Community
  • 1
  • 1
DeBaze
  • 343
  • 1
  • 14
  • 3
    Try using `setTimeout(function() { ... do stuff }, ms)`. – Sergiu Paraschiv Jul 10 '15 at 12:11
  • problem is I just want to pause the code, so a callback is no option here, but thanks for the suggestion – DeBaze Jul 10 '15 at 12:14
  • 2
    While achievable, pausing the whole UI thread is pretty bad. http://stackoverflow.com/questions/951021/what-do-i-do-if-i-want-a-javascript-version-of-sleep Why? Because it will block everything else, including `click` event handlers for example. If blocking user interaction is what you need then maybe try _disabling_ the events themselves. – Sergiu Paraschiv Jul 10 '15 at 12:15
  • Replace `pauseMs` with `setTimeout(function(){//Code}, 500)` and replace `//Code` with your code that you want to execute after 500ms. – Utkarsh Vishnoi Jul 10 '15 at 12:16
  • you can't stop javascript from keep going there isn't possibilty to make it sleep like we do on server side .your only option is setTimeout callback where the rest of the code will be. – baaroz Jul 10 '15 at 12:20
  • 1
    Interesting point Sergiu. Thanks for the link to the SO question. That made clear that the pauseMs function blocks the browser from updating the DOM. It is indeed blocking user interaction that I want to archieve. I'll have to rethink my code to use this setTimeout( callback(), ..) Thanks again I think I can accept this as an answer – DeBaze Jul 10 '15 at 12:21
  • @Sergiu : I managed to refactor the code as you suggested, disabling the event listeners, then call the setTimeout to enable them again and continue after the required time. Your suggestion saved me a lot of time as I was somehow stuck with this pauseMS function, which I found in a blogpost without warning for adverse effects. Thanks a lot! – DeBaze Jul 10 '15 at 12:44

0 Answers0