代码之家  ›  专栏  ›  技术社区  ›  Abhishek

超时未按预期工作

  •  0
  • Abhishek  · 技术社区  · 7 年前

    console.time("Time");
    var i=0;
    setTimeout(function(){console.log("Timeout...")},500);
    
    while(true){
      if(i==1000000000){
        console.timeEnd("Time");
        console.log("whileloop breaking...");
        break;
      }
      else{i++;}
    }

    暂停 在0.5秒后的控制台中,有一个while循环在大约2秒后终止,我通过记录花费的时间来显示。我预料到了 暂停 同时断开回路 同时断开回路 暂停 ...有人能解释一下这段代码的堆栈跟踪或流吗。

    3 回复  |  直到 7 年前
        1
  •  2
  •   L.Wonbae    7 年前

    首先,我英语说得不太好。 但我想帮你

    如果第一个任务正在运行,则将保留所有事件

    您声明了setTimeout 但是,此setTimeout在0.5s内运行

    因为whileloop在单线程浏览器中只有一个线程

    Wrestling with the Browser Event Queue

    Concurrency model and Event Loop

        2
  •  0
  •   Nemani    7 年前

    以下是可视化运行上述代码时发生的事情的最佳方法:

    http://latentflip.com/loupe/?code=Y29uc29sZS50aW1lKCJUaW1lIik7DQp2YXIgaT0wOw0Kc2V0VGltZW91dChmdW5jdGlvbigpe2NvbnNvbGUubG9nKCJUaW1lb3V0Li4uIil9LDUwMCk7DQoNCndoaWxlKHRydWUpew0KICBpZihpPT0xMDAwMDAwMDAwKXsNCiAgICBjb25zb2xlLnRpbWVFbmQoIlRpbWUiKTsNCiAgICBjb25zb2xlLmxvZygid2hpbGVsb29wIGJyZWFraW5nLi4uIik7DQogICAgYnJlYWs7DQogIH0NCiAgZWxzZXtpKys7fQ0KfQ0KIA%3D%3D!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D

        console.time("Time");
            var i=0;
            //here a callback is registered and should be called when timer expires
            setTimeout(function(){console.log("Timeout...")},500);
    
            //since settimeout is async in nature, main thread continues 
        //to execute new line of code i.e. while loop
            // After 500 ms when timer expires, it puts the callback in event queue, 
        // the callback will be executed as soon as it sees the main thread free, but since 
    //while loop is running on main thread for 2sec, the main thread will be free //only after 2 sec (or while loop) finishes.
            while(true){
              if(i==1000000000){
                console.timeEnd("Time");
                console.log("whileloop breaking...");
                break;
              }
              else{i++;}
            }
            // as there is no code to be executed now, main thread takes new task from 
            // event Queue, in this case the new task is callback from settimeout.
    

    我希望这能帮助你了解一点关于settimeout的内容

        3
  •  0
  •   Sachin    7 年前

    但是如果你想打印 暂停 首先,然后 同时断开回路 在你的代码中,然后试试这个--

    console.time("Time");
    var i=0;
    //setTimeout(function(){console.log("Timeout...")},500);
    setTimeout(console.log("Timeout..."),500);
    
    while(true){
      if(i==1000000000){
        console.timeEnd("Time");
        console.log("whileloop breaking...");
        break;
      }
      else{i++;}
    }

    我刚搬走 function(){} setTimeout ..