在 x 毫秒后强制 JavaScript setTimeout 函数为 运行

Force JavaScript setTimout function to run after x miliseconds

我正在尝试制作一个超时函数,该函数会在函数挂起时间过长时抛出错误。

我有以下代码:

function go() {

  try{
    console.log('started, timeout in 2 seconds...');
    setTimeout(()=>{
      throw new Error('Timed Out!');
    }, 2000);

    while(true){
      //will run forever
    }
  }catch (e) {
    console.log('timeout function worked!');
  }
}

go();

但是,永远不会抛出错误。我认为这是因为事件循环在 JS 中的工作方式,但我希望我的超时函数在 2 秒后执行,而不管发生了什么。我该如何实现?

I'd like for my timeout function to execute after 2 seconds regardless of what else is happening. How do I achieve this?

你真的不能。如您所料,问题与事件循环有关。只有一个线程可供您使用,您已将其置于无限循环中。因为你从来没有 return,事件循环没有机会 运行 由 setTimeout 指定的函数。

如果你想让你的 while 循环停止,你的 while 循环需要是停止它的那个。也许是这样的:

const before = Date.now();
while (true) {
  // do stuff
  if (Date.now() - before > 2000) {
    throw new Error('Timed Out!');
  }
}

我认为这是因为你首先进入无限循环并且永远不会退出,所以你的 settimeout 永远不会触发。

我不知道你想达到什么目的,但如果你想抛出错误,最后将 while 循环移到 settimeout 中。 顺便说一句没有意义

setTimeout() 并不像您想象的那样有效。直到while循环为运行。 setTimeout() 函数不会被调用。

Javascript doesnot support multithreading because it is an interpreted language. Multithreading: is a type of execution model that allows multiple threads to exist.See more

下面是例子。

function loop(){
  console.time('time');
  for(let i = 0;i<10000000;i++){
    if(i % 2000000 === 0) console.log("I am looping");
  }
  console.timeEnd('time');
  console.log("Loop finished");
}
loop();
setTimeout(() => {
  console.log("I am logged from setTimeout")
},0)

如果事件循环无法继续,您将无能为力。但是,下面的代码应该更接近您正在寻找的内容。如果你需要做一个while语句,再往下做代码。

function go() {
  try{
    var timeout = setTimeout(()=>{
      throw new Error('Timed Out!');
    }, 2000);

    //do stuff; it can't hog the event loop
  }catch(e){
    
  }
  clearTimeout(timeout);
  return true; //return value
}

go();

var iterations = 0;
while(condition && iterations < 10){
  //do stuff
  iterations++;
}