如何创建javascript延迟函数 [英] How to create javascript delay function

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

问题描述

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

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
}

但是,我找不到任何方法来实现代码以使其等待.我查看了 setTimeout,但您需要将函数硬编码到其中,这对我不利.

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.

有什么办法可以让脚本暂停几秒钟?代码暂停时 UI 冻结没有问题.

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.

如果没有,有没有办法可以使用 PHP sleep() 来实现这一点?(我知道 PHP 是服务器端而 Javascript 是客户端,但也许有一种我没有听说过的方法.)

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.)

推荐答案

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

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天全站免登陆