如何创建JavaScript延迟功能 [英] How to create javascript delay function

查看:108
本文介绍了如何创建JavaScript延迟功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript文件,并且在几个地方我想添加一个小延迟,所以脚本会到达这一点,等待3秒钟,然后继续执行其余的代码。我想这样做的最好方法是创建一个函数,我可以在脚本的任何地方调用它。

 函数startDelay(lengthOfDelay)
{
//使它延迟lengthOfDelay时间量的代码
}

但是,我找不到任何方法来实现代码以使其等待。我看了一下setTimeout,但是你需要对函数进行硬编码,这对我没有好处。



有什么方法可以获得脚本停顿几秒钟?



如果不是,有没有一种方法可以使用PHP sleep()要实现这一目标? (我知道PHP是服务器端,Javascript是客户端,但也许有一种我没有听说过的方法。)

您不需要使用 setTimeout 的匿名函数。你可以这样做:

  setTimeout(doSomething,3000); 

函数doSomething(){
//做任何你想在这里
}


I have a javascript file, and in several places I want to add a small delay, so the script would reach that point, wait 3 seconds, and then continue with the rest of the code. The best way that I thought of doing this was to create a function, which I could call from anywhere in the script.

function startDelay(lengthOfDelay)
{
//code to make it delay for lengthOfDelay amount of time
}

However, I can not find any way to implement the code to make it wait. I had a look at setTimeout, but you needed to hard code the function into it, which made it no good for me.

Is there any way that I can get the script to juct pause for a few seconds? I have no problem with the UI freezing whilst the code is paused.

If not, is there a way that I could use the PHP sleep() to achieve this? (I know that PHP is server side and Javascript is client side, but maybe there is a way that I have not heard of.)

解决方案

You do not need to use an anonymous function with setTimeout. You can do something like this:

setTimeout(doSomething, 3000);

function doSomething() {
   //do whatever you want here
}

这篇关于如何创建JavaScript延迟功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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