代码执行中的同步延迟 [英] Synchronous delay in code execution

查看:94
本文介绍了代码执行中的同步延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码需要在延迟说5000 ms后执行。目前我使用的是setTimeout但它是异步的,我希望执行等待它的返回。我尝试过使用以下内容:

I have a code which needs to be executed after some delay say 5000 ms.Currently I am using setTimeout but it is asynchronous and i want the execution to wait for its return. I have tried using the following:

function pauseComp(ms) 
 {
     var curr = new Date().getTime();
     ms += curr;
     while (curr   < ms) {
         curr = new Date().getTime();
     }
 } 

但我想延迟的代码是绘制一些对象使用raphaeljs和显示器一点也不顺利。我正在尝试使用doTimeout插件。我只需要延迟一次,因为延迟和要延迟的代码都在循环中。我没有要求身份证,所以我没有使用它。
例如:

But the code i want to delay is drawing some objects using raphaeljs and the display is not at all smooth. I am trying to use doTimeout plugin. I need to have a delay only once as the delay and code to be delayed are both in a loop. I have no requirement for a id so I am not using it. For example:

for(i; i<5; i++){ $.doTimeout(5000,function(){
         alert('hi');  return false;}, true);}

等待5秒钟,然后给出第一个Hi,然后连续循环迭代在第一个之后立即显示警报。我想要它做的是等待5秒再次提醒警报等待然后提供警报等等。

This waits for 5 sec befor giving first Hi and then successive loop iterations show alert immediately after the first. What I want it to do is wait 5 sec give alert again wait and then give alert and so on.

任何提示/建议都表示赞赏!

Any hints/ suggestions are appreciated!

推荐答案

接受的回答和这个一样好。

Variation on the accepted answer which is just as good as this one.

另外,我同意更喜欢 setTimeout 的注意事项,异步函数调用但有时例如,在构建测试时,您只需要一个同步等待命令...

Also, I agree with the caveats of preferring setTimeout and asynchronous function calling but sometimes e.g., when building tests, you just need a synchronous wait command...

function wait(ms) {
    var start = Date.now(),
        now = start;
    while (now - start < ms) {
      now = Date.now();
    }
}

如果你想要它在几秒钟内,除以开始ms同时检查1000 ...

if you want it in seconds, divide start ms by 1000 on the while check...

这篇关于代码执行中的同步延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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