Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create javascript delay function [duplicate]

Tags:

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

like image 463
user2370460 Avatar asked Jun 01 '13 14:06

user2370460


People also ask

How do you make a delay in JavaScript?

The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console. log("Hello"); setTimeout(() => { console.

What is delay () in JavaScript?

Conclusion. setTimeout() is a method that will execute a piece of code after the timer has finished running. let timeoutID = setTimeout(function, delay in milliseconds, argument1, argument2,...); The delay is set in milliseconds and 1,000 milliseconds equals 1 second.

How do you create a delay in a loop?

Another way is to multiply the time to timeout, but note that this is not like sleep. Code after the loop will be executed immediately, only the execution of the callback function is deferred. for (var start = 1; start < 10; start++) setTimeout(function () { alert('hello'); }, 3000 * start);


2 Answers

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 } 
like image 107
Kassem Avatar answered Oct 16 '22 09:10

Kassem


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.

like image 40
DanRedux Avatar answered Oct 16 '22 09:10

DanRedux