<p>Is there any JavaScript method similar to the jQuery <code>delay()</code> or <code>wait()</code> (to delay the execution of a script for a specific amount of time)?</p>

[{'answer_id': 24850, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 4, 'selected': False, 'text': '<p>You need to use <a href="http://www.w3schools.com/jsref/met_win_settimeout.asp" rel="noreferrer">setTimeout</a> and pass it a callback function. The reason you can\'t use sleep in javascript is because you\'d block the entire page from doing anything in the meantime. Not a good plan. Use Javascript\'s event model and stay happy. Don\'t fight it!</p>\n'}, {'answer_id': 24852, 'author': 'Abhinav', 'author_id': 2617, 'author_profile': 'https://Stackoverflow.com/users/2617', 'pm_score': 9, 'selected': True, 'text': '<p>There is the following:</p>\n\n<pre><code>setTimeout(function, milliseconds);\n</code></pre>\n\n<p>function which can be passed the time after which the function will be executed.</p>\n\n<p>See: <a href="https://www.w3schools.com/jsref/met_win_settimeout.asp" rel="noreferrer">Window <code>setTimeout()</code> Method</a>.</p>\n'}, {'answer_id': 24862, 'author': 'rcoup', 'author_id': 2662, 'author_profile': 'https://Stackoverflow.com/users/2662', 'pm_score': 4, 'selected': False, 'text': '<p>You can also use <a href="http://www.devguru.com/Technologies/ecmascript/quickref/win_setinterval.html" rel="noreferrer">window.setInterval()</a> to run some code repeatedly at a regular interval.</p>\n'}, {'answer_id': 24934, 'author': 'Polsonby', 'author_id': 137, 'author_profile': 'https://Stackoverflow.com/users/137', 'pm_score': 5, 'selected': False, 'text': '<p>Just to expand a little... You can execute code directly in the <code>setTimeout</code> call, but as <a href="https://stackoverflow.com/questions/24849/is-there-some-way-to-introduce-a-delay-in-javascript#24850">@patrick</a> says, you normally assign a callback function, like this. The time is milliseconds</p>\n\n<pre><code>setTimeout(func, 4000);\nfunction func() {\n    alert(\'Do stuff here\');\n}\n</code></pre>\n'}, {'answer_id': 24953, 'author': 'Marius', 'author_id': 1585, 'author_profile': 'https://Stackoverflow.com/users/1585', 'pm_score': 8, 'selected': False, 'text': '<p>Just to add to what everyone else have said about <code>setTimeout</code>:\nIf you want to call a function with a parameter in the future, you need to set up some anonymous function calls. </p>\n\n<p>You need to pass the function as an argument for it to be called later. In effect this means without brackets behind the name. The following will call the alert at once, and it will display \'Hello world\':</p>\n\n<pre><code>var a = "world";\nsetTimeout(alert("Hello " + a), 2000);\n</code></pre>\n\n<p>To fix this you can either put the name of a function (as Flubba has done) or you can use an anonymous function. If you need to pass a parameter, then you have to use an anonymous function.</p>\n\n<pre><code>var a = "world";\nsetTimeout(function(){alert("Hello " + a)}, 2000);\na = "Stack Overflow";\n</code></pre>\n\n<p>But if you run that code you will notice that after 2 seconds the popup will say \'Hello Stack Overflow\'. This is because the value of the variable a has changed in those two seconds. To get it to say \'Hello world\' after two seconds, you need to use the following code snippet:</p>\n\n<pre><code>function callback(a){\n    return function(){\n        alert("Hello " + a);\n    }\n}\nvar a = "world";\nsetTimeout(callback(a), 2000);\na = "Stack Overflow";\n</code></pre>\n\n<p>It will wait 2 seconds and then popup \'Hello world\'.</p>\n'}, {'answer_id': 8783433, 'author': 'narasi', 'author_id': 1137896, 'author_profile': 'https://Stackoverflow.com/users/1137896', 'pm_score': 4, 'selected': False, 'text': "<p>To add on the earlier comments, I would like to say the following : </p>\n\n<p>The <code>setTimeout()</code> function in JavaScript does not pause execution of the script per se, but merely tells the compiler to execute the code sometime in the future.</p>\n\n<p>There isn't a function that can actually pause execution built into JavaScript. However, you can write your own function that does something like an unconditional loop till the time is reached by using the <code>Date()</code> function and adding the time interval you need.</p>\n"}, {'answer_id': 24488671, 'author': 'Mario Werner', 'author_id': 2746541, 'author_profile': 'https://Stackoverflow.com/users/2746541', 'pm_score': 5, 'selected': False, 'text': '<p>If you really want to have a blocking (synchronous) <code>delay</code> function (for whatsoever), why not do something like this:</p>\n\n<pre><code>&lt;script type="text/javascript"&gt;\n    function delay(ms) {\n        var cur_d = new Date();\n        var cur_ticks = cur_d.getTime();\n        var ms_passed = 0;\n        while(ms_passed &lt; ms) {\n            var d = new Date();  // Possible memory leak?\n            var ticks = d.getTime();\n            ms_passed = ticks - cur_ticks;\n            // d = null;  // Prevent memory leak?\n        }\n    }\n\n    alert("2 sec delay")\n    delay(2000);\n    alert("done ... 500 ms delay")\n    delay(500);\n    alert("done");\n&lt;/script&gt;\n</code></pre>\n'}, {'answer_id': 27576023, 'author': 'Christoffer', 'author_id': 632182, 'author_profile': 'https://Stackoverflow.com/users/632182', 'pm_score': 3, 'selected': False, 'text': '<p>If you only need to test a delay you can use this:</p>\n\n<pre><code>function delay(ms) {\n   ms += new Date().getTime();\n   while (new Date() &lt; ms){}\n}\n</code></pre>\n\n<p>And then if you want to delay for 2 second you do:</p>\n\n<pre><code>delay(2000);\n</code></pre>\n\n<p>Might not be the best for production though. More on that in the comments</p>\n'}, {'answer_id': 35230867, 'author': 'JohnnyIV', 'author_id': 4133108, 'author_profile': 'https://Stackoverflow.com/users/4133108', 'pm_score': 1, 'selected': False, 'text': '<p>I had some ajax commands I wanted to run with a delay in between.  Here is a simple example of one way to do that.  I am prepared to be ripped to shreds though for my unconventional approach.  :)</p>\n\n<pre><code>//  Show current seconds and milliseconds\n//  (I know there are other ways, I was aiming for minimal code\n//  and fixed width.)\nfunction secs()\n{\n    var s = Date.now() + ""; s = s.substr(s.length - 5);\n  return s.substr(0, 2) + "." + s.substr(2);\n}\n\n//  Log we\'re loading\nconsole.log("Loading: " + secs());\n\n//  Create a list of commands to execute\nvar cmds = \n[\n    function() { console.log("A: " + secs()); },\n    function() { console.log("B: " + secs()); },\n    function() { console.log("C: " + secs()); },\n    function() { console.log("D: " + secs()); },\n    function() { console.log("E: " + secs()); },\n  function() { console.log("done: " + secs()); }\n];\n\n//  Run each command with a second delay in between\nvar ms = 1000;\ncmds.forEach(function(cmd, i)\n{\n    setTimeout(cmd, ms * i);\n});\n\n// Log we\'ve loaded (probably logged before first command)\nconsole.log("Loaded: " + secs());\n</code></pre>\n\n<p>You can copy the code block and paste it into a console window and see something like:</p>\n\n<pre><code>Loading: 03.077\nLoaded: 03.078\nA: 03.079\nB: 04.075\nC: 05.075\nD: 06.075\nE: 07.076\ndone: 08.076\n</code></pre>\n'}, {'answer_id': 41667568, 'author': 'Al Joslin', 'author_id': 2912739, 'author_profile': 'https://Stackoverflow.com/users/2912739', 'pm_score': 3, 'selected': False, 'text': '<p>why can\'t you put the code behind a promise? (typed in off the top of my head)</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>new Promise(function(resolve, reject) {\r\n  setTimeout(resolve, 2000);\r\n}).then(function() {\r\n  console.log(\'do whatever you wanted to hold off on\');\r\n});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 41785515, 'author': 'Luca', 'author_id': 410354, 'author_profile': 'https://Stackoverflow.com/users/410354', 'pm_score': 3, 'selected': False, 'text': '<p>The simple reply is: </p>\n\n<pre><code>setTimeout(\n    function () {\n        x = 1;\n    }, 1000);\n</code></pre>\n\n<p>The function above waits for 1 second (1000 ms) then sets x to 1. \nObviously this is an example; you can do anything you want inside the anonymous function. </p>\n'}, {'answer_id': 47213654, 'author': 'Doug', 'author_id': 8027640, 'author_profile': 'https://Stackoverflow.com/users/8027640', 'pm_score': 2, 'selected': False, 'text': "<p>I really liked Maurius' explanation (highest upvoted response) with the three different methods for calling <code>setTimeout</code>.  </p>\n\n<p>In my code I want to automatically auto-navigate to the previous page upon completion of an AJAX save event.  The completion of the save event has a slight animation in the CSS indicating the save was successful.</p>\n\n<p>In my code I found a difference between the first two examples: </p>\n\n<pre><code>setTimeout(window.history.back(), 3000);\n</code></pre>\n\n<p>This one does not wait for the timeout--the back() is called almost immediately no matter what number I put in for the delay.</p>\n\n<p>However, changing this to:</p>\n\n<pre><code>setTimeout(function() {window.history.back()}, 3000);\n</code></pre>\n\n<p>This does exactly what I was hoping.</p>\n\n<p>This is not specific to the back() operation, the same happens with <code>alert()</code>.  Basically with the <code>alert()</code> used in the first case, the delay time is ignored.  When I dismiss the popup the animation for the CSS continues.</p>\n\n<p>Thus, I would recommend the second or third method he describes even if you are using built in functions and not using arguments.</p>\n"}, {'answer_id': 51450886, 'author': 'JavaSheriff', 'author_id': 648026, 'author_profile': 'https://Stackoverflow.com/users/648026', 'pm_score': 2, 'selected': False, 'text': '<p>As other said, setTimeout is your safest bet<br>\nBut sometimes you cannot separate the logic to a new function then you can use Date.now() to get milliseconds and do the delay yourself....</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function delay(milisecondDelay) {\r\n   milisecondDelay += Date.now();\r\n   while(Date.now() &lt; milisecondDelay){}\r\n}\r\n\r\nalert(\'Ill be back in 5 sec after you click OK....\');\r\ndelay(5000);\r\nalert(\'# Im back # date:\' +new Date());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 54499594, 'author': 'Jackkobec', 'author_id': 9477038, 'author_profile': 'https://Stackoverflow.com/users/9477038', 'pm_score': 1, 'selected': False, 'text': '<p>The simplest solution to call your function with delay is:</p>\n\n<pre><code>function executeWithDelay(anotherFunction) {\n    setTimeout(anotherFunction, delayInMilliseconds);\n}\n</code></pre>\n'}, {'answer_id': 57497385, 'author': 'Zuhair Taha', 'author_id': 1274894, 'author_profile': 'https://Stackoverflow.com/users/1274894', 'pm_score': 2, 'selected': False, 'text': '<p>delay function:</p>\n<pre class="lang-js prettyprint-override"><code>/**\n * delay or pause for some time\n * @param {number} t - time (ms)\n * @return {Promise&lt;*&gt;}\n */\nconst delay = async t =&gt; new Promise(resolve =&gt; setTimeout(resolve, t));\n</code></pre>\n<p>usage inside <code>async</code> function:</p>\n<pre class="lang-js prettyprint-override"><code>await delay(1000);\n</code></pre>\n<p>Or</p>\n<pre class="lang-js prettyprint-override"><code>delay(1000).then(() =&gt; {\n   // your code...\n});\n</code></pre>\n<p>Or without a function</p>\n<pre class="lang-js prettyprint-override"><code>new Promise(r =&gt; setTimeout(r, 1000)).then(() =&gt; {\n   // your code ...\n});\n// or\nawait new Promise(r =&gt; setTimeout(r, 1000));\n// your code...\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/24849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184/']