javascript 如何创建javascript延迟函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16873889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:18:28  来源:igfitidea点击:

How to create javascript delay function

javascriptfunctiondelaysleepwait

提问by user2370460

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.

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

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.

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

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.

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

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

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

回答by Kassem

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

您不需要将匿名函数与setTimeout. 你可以这样做:

setTimeout(doSomething, 3000);

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

回答by DanRedux

Ah yes. Welcome to Asynchronous execution.

没错。欢迎使用异步执行。

Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.

基本上,暂停脚本会导致浏览器和页面无响应 3 秒。这对于网络应用程序来说太可怕了,因此不受支持。

Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.

相反,您必须考虑“基于事件”。使用 setTimeout 在一定时间后调用函数,该函数将在此期间继续运行页面上的 JavaScript。

回答by CBC_NS

You can create a delay using the following example

您可以使用以下示例创建延迟

setInterval(function(){alert("Hello")},3000);

Replace 3000with # of milliseconds

替换3000与#毫秒

You can place the content of what you want executed inside the function.

您可以将要执行的内容放在函数内。