Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute window.prompt after some operations are completed?

Tags:

javascript

The code just like this:

for(var node=iterator.iterateNext(),origin_background=node.style.background;node;node=iterator.iterateNext())
{
    console.log('change color.');
    node.style.background="#3E6998";
}
var input_str=window.prompt('Next Step?\n1....');
if(input_str=='1')
    ...

When I execute it in Chrome console, the prompt arises but the background was still not changed. How to modify the code so that the background change before prompt arise?

like image 880
0x3E6 Avatar asked Feb 01 '26 04:02

0x3E6


1 Answers

DOM manipulations are synchronous but their repaint isn't. That means that they [the repaints] are not applied immediately, they're just pushed into a stack of todos that the browser will do when it has [free] time. Those kind of asynchronous jobs don't have a callback to use when they're done, so the only thing we can do to make sure something runs after they're done is pushing that something to the stack of todos. We can do that by using a setTimeout with a delay of 0:

var div = document.getElementById("div");

div.style.background = "green";

setTimeout(function() {
  var name = prompt("Name?");
  console.log(name);
}, 0);
#div {
  width: 200px;
  height: 200px;
  background: red;
}
<div id="div"></div>
like image 175
ibrahim mahrir Avatar answered Feb 02 '26 17:02

ibrahim mahrir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!