javascript中2行代码之间的时间延迟,而不是settimeout [英] time delay between 2 lines of code in javascript, not settimeout

查看:72
本文介绍了javascript中2行代码之间的时间延迟,而不是settimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我正在寻找像这样的伪代码

I am looking for something like this pseudo code

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

TIA

编辑:
jimr在我的其他主题中的解决方案适用于我的目的,Robusto也是如此。

jimr's solution in my other thread worked for my purpose, and so is Robusto's.

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

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.)

推荐答案

以下是<强大,笨重,丑陋,我永远不会在我自己的代码中做到这一点,我不推荐它,但它表明这样的事情是可能的。

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();
  }
}

这篇关于javascript中2行代码之间的时间延迟,而不是settimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆