如何在函数运行后等待一段时间 [英] How to wait for a period of time after a function run

查看:118
本文介绍了如何在函数运行后等待一段时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个函数,我希望我的js代码立即运行,但运行后,等待2秒。如何实现这个逻辑?

If I have a function which I would like my js code to run it immediately but after the run, wait for 2 seconds. How to achieve this logic?

注意:这只是与 setTimeout()的逆逻辑比较,因为 setTimeout()首先等待一段时间然后执行该函数。)

(Note: It is just the inverse logic compare with setTimeout(), since setTimeout() first wait a certain amount of time then execute the function.)

推荐答案

只需将您的代码放入传递给setTimeout的匿名函数中。

Just put your code inside an anonymous function passed to setTimeout.

例如

functionToRunFirst();
setTimeout(function() {
    // rest of code here
}, 2000);

这篇关于如何在函数运行后等待一段时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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