在JavaScript中睡眠 - 在动作之间延迟 [英] Sleep in JavaScript - delay between actions

查看:137
本文介绍了在JavaScript中睡眠 - 在动作之间延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在执行其他操作之前,有没有办法让我在JavaScript中睡觉?

Is there a way I can do a sleep in JavaScript before it carries out another action?

示例:

 var a = 1+3;
 // Sleep 3 seconds before the next action here
 var b = a + 4;


推荐答案

您可以使用 setTimeout 实现类似的效果:

You can use setTimeout to achieve a similar effect:

var a = 1 + 3;
var b;
setTimeout(function() {
    b = a + 4;
}, (3 * 1000));

这不是'睡眠'JavaScript - 它只是执行传递给<$ c $的函数c> setTimeout 经过一段时间(以毫秒为单位)。尽管可以为JavaScript编写睡眠函数,但最好使用 setTimeout ,因为它不会在睡眠期间冻结所有内容。

This doesn't really 'sleep' JavaScript—it just executes the function passed to setTimeout after a certain duration (specified in milliseconds). Although it is possible to write a sleep function for JavaScript, it's best to use setTimeout if possible as it doesn't freeze everything during the sleep period.

这篇关于在JavaScript中睡眠 - 在动作之间延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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