JavaScript:函数按不同顺序激发

JavaScript:函数按不同顺序激发,javascript,events,Javascript,Events,我不明白为什么函数alert()在该代码中将style设置为指示器之前会触发: JavaScript: var MyClass = function() { th = this; th.func = function(){alert('yes');}; th.Click = function(){ document.getElementById('indicator').style.color = "#0f0"; document.getElementB

我不明白为什么函数
alert()
在该代码中将style设置为
指示器之前会触发:

JavaScript:

var MyClass = function()
{
  th       = this;
  th.func  = function(){alert('yes');};
  th.Click = function(){
    document.getElementById('indicator').style.color = "#0f0";
    document.getElementById('indicator').innerHTML = "YES";
    th.func();     // here it fires before above style changing
  };
  th.Start = function()
  {
    var a  = document.getElementById('button1');
    a.addEventListener('click', th.Click, false);
  };
  th.Init  = function()
  {
    th.Start();
  };
}
var a = new MyClass().Init();
<button id='button1'>Click Me</button>
<div id='indicator' style='color:#f00'>NO</div>
Html:

var MyClass = function()
{
  th       = this;
  th.func  = function(){alert('yes');};
  th.Click = function(){
    document.getElementById('indicator').style.color = "#0f0";
    document.getElementById('indicator').innerHTML = "YES";
    th.func();     // here it fires before above style changing
  };
  th.Start = function()
  {
    var a  = document.getElementById('button1');
    a.addEventListener('click', th.Click, false);
  };
  th.Init  = function()
  {
    th.Start();
  };
}
var a = new MyClass().Init();
<button id='button1'>Click Me</button>
<div id='indicator' style='color:#f00'>NO</div>
点击我
不

我想让它在之后开火

这是因为Javascript的单线程特性。“警报/模式”窗口实际上会停止其他所有操作,直到它被取消

这包括颜色的变化。Javascript实际上表示浏览器开始更改颜色并继续,但当它遇到警报时,颜色的更改或发生的任何过程都将暂停,并且在模式窗口aka警报解除之前不会再次开始。解决方法可能是执行以下操作:


点击我
不
var MyClass=function(){
th=这个;
th.func=function(){window.alert('yes');};
th.Click=函数(){
document.getElementById('indicator').style.color=“#0f0”;
document.getElementById('indicator').innerHTML=“是”;
//设置超时修复
// ====
设置超时(th.func,100);
};
th.Start=函数()
{
var a=document.getElementById('button1');
a、 addEventListener('click',th.click,false);
};
th.Init=函数()
{
th.Start();
};
}
var a=new MyClass().Init();

它会在之后触发,但您所经历的是“线程阻塞”。警报()将停止当前页面上浏览器的所有操作。因此,它还阻止了内容的重画。您可以通过使用非阻塞调用来进行检查,例如
window.setTimeout(th.func,0)
@devnull69,因此如果它是不同的函数,例如
GET()
request而不是
alert()
,它将按正常顺序运行?是的,您是正确的,但仅适用于异步方法。对于每一个同步的,如果您不使用example@devnull69如果不使用
setTimeout()
,我怎么做?我的意思是,做任何事情(异步/同步),但只能在设置样式之后,在相同的函数中。。如果不能在同一个函数中执行,那么这样做的好例子是什么?这是单线程Javascript的本质。只有当线程有时间更新视图时,才能确保视图更新。只要你的代码不间断地运行(即asnycronouos方法调用或一些用户交互),它就没有时间去做。好的。最后一个问题:例如,我有一台速度非常慢的机器(或负载非常大),我们这里不仅有样式更改,还有超时前的大函数,我将超时设置为
1
,即使在这些条件下,它也会启动吗?无论发生什么情况,setTimeout代码都会在下一个处理器周期(勾号)中执行。例如:
setTimeout(()=>{alert(“Hi”);},0);警惕(“你好!”)在这里,实际上“嗨”的警报应该首先起作用,因为我们必须等待0秒,但是“你好!”首先起作用是的,我做了一个循环,效果很好,谢谢你的帮助!;)