Javascript javascript中两行代码之间的时间延迟,而不是settimeout

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3048724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:04:57  来源:igfitidea点击:

time delay between 2 lines of code in javascript, not settimeout

javascript

提问by Jamex

is there a function that would add a time delay between 2 lines of code. Not the settimeout, because settimeout requires a function/object in its arguments.

是否有一个函数可以在两行代码之间添加时间延迟。不是 settimeout,因为 settimeout 在其参数中需要一个函数/对象。

I am looking for something like this pseudo code

我正在寻找类似这个伪代码的东西

write "abc";
delay(500);
write "xyz";

TIA

TIA

Edit: jimr's solution in my other threadworked for my purpose, and so is Robusto's.

编辑:jimr 在我的另一个线程中的解决方案适用于我的目的,Robusto 的 也是如此。

I am just wondering why the "sleep" methods given by Robusto and CMS's link are not preferred. How would that be different than the settimeout method since they both introduce a pause in the code? (settimeout pauses before the function is executed, the sleep method pauses before the next line is executed.)

我只是想知道为什么 Robusto 和 CMS 的链接给出的“睡眠”方法不是首选。这与 settimeout 方法有何不同,因为它们都在代码中引入了暂停?(settimeout在函数执行前暂停,sleep方法在下一行执行前暂停。)

回答by Robusto

The following is clunky and ugly and I would never do it in my own code and I DO NOT RECOMMEND IT AT ALL, but it shows that such a thing is possible.

下面是笨重和丑陋的,我永远不会在我自己的代码中这样做,我根本不推荐它,但它表明这样的事情是可能的。

// time arg is in milliseconds
function delay(time) {
  var d1 = new Date();
  var d2 = new Date();
  while (d2.valueOf() < d1.valueOf() + time) {
    d2 = new Date();
  }
}

回答by Joel Coehoorn

You can use setTimeout so that it almost appears the code runs on two lines:

您可以使用 setTimeout 使代码几乎显示在两行上:

write('abc')
setTimeout(function() {
write('xyz')
},500)

回答by Tobias P.

A sleep-Method is not available because JavaScript execution blocks the browser, so a sleep-Method would block the browser for 500msec, do you really want to have your browser not responding for half an second?

sleep-Method 不可用,因为 JavaScript 执行会阻塞浏览器,所以 sleep-Method 会阻塞浏览器 500 毫秒,你真的想让你的浏览器半秒不响应吗?

Use setTimeout as suggested.

按照建议使用 setTimeout。

回答by Eli Grey

In JavaScript 1.7, using yieldwith async.js, you can do the following:

在 JavaScript 1.7 中,yieldasync.js 一起使用,您可以执行以下操作:

var yourFunction = _(function () {
    write("abc");
    yield to.sleep(.500);
    write("xyz");
});

回答by Anurag

I don't know what you're trying to do here, but here's one concrete reason for why a custom sleep may not work for your purposes assuming the browser freezing up is a non-issue for you.

我不知道你在这里想做什么,但这里有一个具体的原因,为什么自定义睡眠可能无法满足你的目的,假设浏览器冻结对你来说不是问题。

Are you manipulating the DOM by any chance between those two write commands? If you are, then it simply will not work (as perceived by an end user), although the DOM nodes will be constructed/updated in memory, the display will not get updated as that part is not synchronous. The processor is locked up in that loop, and both the DOM updates will refresh on screen when that loop finishes. See this example.

您是否有机会在这两个写入命令之间操作 DOM?如果是,那么它根本无法工作(如最终用户所认为的那样),尽管 DOM 节点将在内存中构建/更新,但显示不会更新,因为该部分不是同步的。处理器被锁定在该循环中,当该循环完成时,两个 DOM 更新都将在屏幕上刷新。请参阅此示例

Ideally, you should see "Hello", and after 5 seconds, "World" on the screen. However, on Chrome, Safari, and Firefox, you would see both "Hello" and "World" at the end of 5 seconds. The console logs prove that the DOM node is constructed in memory, but is not refreshed on screen until the end as you can see yourself.

理想情况下,您应该在屏幕上看到“Hello”,并在 5 秒后看到“World”。但是,在 Chrome、Safari 和 Firefox 上,您会在 5 秒结束时看到“Hello”和“World”。控制台日志证明 DOM 节点是在内存中构建的,但直到最后才会在屏幕上刷新,如您所见。

回答by Hooray Im Helping

As far as I know, setTimeout()is the only way to do it.

据我所知,这setTimeout()是唯一的方法。

function write(out) {
  alert(out);
}

// ...

write('abc');
setTimeout(function() { write('xyz')}, 500);

回答by Ninjaneer

ES6 Introduced async/awaitwhich can be used to have an actual delay. I have answered this in a different post, just updating here as well

ES6 引入了async/await,可用于实际延迟。我已经在另一篇文章中回答了这个问题,也只是在这里更新

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

异步函数可以包含一个 await 表达式,该表达式暂停异步函数的执行并等待传递的 Promise 的解析,然后恢复异步函数的执行并返回解析的值。

    async function delay(delayInms) {
      return new Promise(resolve  => {
        setTimeout(() => {
          resolve(2);
        }, delayInms);
      });
    }
    async function sample() {
      console.log('a');
      console.log('waiting...')
      let delayres = await delay(3000);
      console.log('b');
    }
    sample();

回答by p.durga shankar

You can add delay using async await concept in JavaScript.

您可以使用 JavaScript 中的 async await 概念添加延迟。

const add2SecondsDelay = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('added 2 seconds delay);
    }, 20000);
  });
}

async function asyncFunctionCall() {

  console.log('abc'); // ------> first step
  const result = await add2SecondsDelay();
  console.log("xyz"); // ------> second step will execute after 2 seconds

}

asyncFunctionCall();

回答by Kyle

I miss that on javascript too, as a java SE and EE enthusiast not having my sleep()makes me disappointed with JavaScript, I made a timer and I hope it can be useful to you, it uses jQuery, and it's fairly simple, you can reverse engineer it and create something that meet your needs:

我也很想念 javascript,作为一个 java SE 和 EE 爱好者,没有sleep()让我对 JavaScript 感到失望,我做了一个计时器,我希望它对你有用,它使用 jQuery,而且相当简单,你可以逆向工程它并创建满足您需求的东西:

function timer(object, time) {
  $(object).attr({
    'onclick': ''
  });
  if (time < 0) {
    $(object).attr({
      'onclick': "timer('#clock', 6000);"
    });
    return;
  }
  $(object).animate({
    opacity: 1
  }, 1, function() {
    $(object).empty();
    $(object).append(time + 'ms');
    time--;
    timer(object, time);
  });
}
#clock {
  width: 65px;
  height: 20px;
  border: 1px solid #F00;
  text-align: center;
  line-height: 20px;
  background-color: #000;
  color: #FFF;
  font-weight: 900;
}
<!DOCTYPE html>
<html>

<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  <title>HTML5, CSS3 and JavaScript demo</title>
</head>

<body>
  <div id="clock" onclick="timer('#clock',6000);">--s</div>
</body>

</html>

回答by yan

setInterval(function delay{ //loops every 300 milliseconds
   setTimeout(function firstLineOfCode(){ //waits 100 milliseconds then runs code
      write('abc');
   },100)
   setTimeout(function secondLineOfCode(){ //waits 200 milliseconds (100 after previous line) then runs code
      write('def');
   },200)
   setTimeout(function thirdLineOfCode(){ //waits 300 milliseconds (100 after previous line) then runs code
      write('ghi');
   },300)
},300) //loops after total of delays in function delay()