Проблема в том, что alert()
отображается программным обеспечением браузера, а не средой выполнения JavaScript или механизмом рендеринга CSS, и часто браузер может работать быстрее / медленнее, чем может выполнять среда выполнения JavaScript.В этом случае alert
визуализируется до того, как среда выполнения JavaScript и движок рендеринга CSS смогут изменить цвет фона.А поскольку alert()
является модальным диалоговым окном, остальная часть пользовательского интерфейса блокируется до тех пор, пока не будет закрыто alert()
, поэтому до этого вы не увидите красный фон.
Решение этой проблемычтобы вручную взять под контроль рендеринг alert()
, отложив его до тех пор, пока текущая функция не будет завершена с таймером:
function runTest() {
$('#test1').css('background-color', 'red');
// Timer callback functions are placed in the event queue and
// won't run until the JavaScript call stack is idle. So,
// makeAlert("test1") won't run until after runTest(), which
// will allow the browser to color the background red before
// the first alert is rendered.
setTimeout(function(){
makeAlert("test1");
}, 100);
}
function makeAlert(msg){
// Now, the first background has been applied and so
// we can ask for the first alert().
alert(msg);
// Now, we'll set the second background color
$('#test2').css('background-color', 'red');
// And defer the second alert until after this function
// is complete.
setTimeout(function(){
alert("test2");
}, 100);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1">test1 test1 test1 test1</div>
<div id="test2">test2 test2 test2 test2</div>
<input type="button" onclick="runTest()" value="start test">