如何在函数运行后等待一段时间

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

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

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

例如

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

我认为你正在寻找的是一种暂停执行代码直到超时的方法。 许多业余程序员都希望有这样的结构,但它在JavaScript中不存在。 这不是必需的。 出于JavaScript的所有目的, setTimeoutsetInterval是完美的候选解决方案。

但是,JavaScript是一种强大的语言。 您可以构建自己的构造来解决此问题。 看看Neil Mix的博客文章 。 通过他的方法,您可以创建一个睡眠function,可以按照以下几行使用(请注意,目前只有Firefox支持JavaScript 1.7):

 function mainGeneratorFunction() { functionToRunFirst(); yield sleep(2000); //rest of the code } 

但是,对于其他浏览器并不绝望。 您可以使用称为XHR Sleeping的黑客。 在这种方法中,您只需使用同步XMLHttpRequest来调用像php这样的服务器端脚本,然后在指定时间内hibernate并在唤醒后返回。 JavaScript代码如下:

 function sleep(microseconds) { var request = new XMLHttpRequest(); request.open("GET", "sleep.php?time=" + microseconds, false); request.send(); } functionToRunFirst(); sleep(2000000); //rest of the code 

php睡眠function如下:

  

使用setTimeout是一种方法

 function run() { // run this code setTimeout(afterTwoSeconds, 2000); } function afterTwoSeconds() { // run this code two seconds after executing run. } // call run run(); 

什么“等待2秒”是什么意思? 你的意思是你想要阻止函数返回2秒钟?

如果是这样,你不能这样做。 JavaScript中没有sleep()函数。

你只需要使用setTimeout()

上面的答案没有错,但不同的方式是:

 $("#somethingThatDoesntExist").fadeTo(2000, 1, function() { // two seconds later }); 

给你一些填写,这应该用半秒计时器运行5次

 var counter = 0; var arrayOfPicture = []; //fill this out function gifSimulator() { //use the counter as an index in the array, and change the image source of your element with that. if (counter < 5) { setTimeout(function () { counter++; gifSimlulator(); }, 500); //lets wait half a second } } 

我不知道你们为什么这么做。 我相信我们可以使用Date对象来做到这一点。 首先获取日期值并使用setInterval函数等待我们获得指定的间隔(获取新日期并检查差异)。 一旦我们重置了间隔function并继续执行代码,之后就可以运行。