How to create javascript delay function [duplicate]

血红的双手。 提交于 2019-12-17 06:10:01

问题


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


回答1:


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
}



回答2:


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.

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.




回答3:


You can create a delay using the following example

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

Replace 3000 with # of milliseconds

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



来源:https://stackoverflow.com/questions/16873889/how-to-create-javascript-delay-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!