Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Wait 1 Second in JavaScript?

#1
How to Wait 1 Second in JavaScript?

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/10/how-to-wait-1-second-in-javascript.jpg" width="550" height="416" title="" alt="" /></div><div><div class="modified-on" readability="7.1304347826087"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on October 18th, 2022.</div>
<p>Wait is there every aspect of human life. Let’s get philosophical for a moment! For every good thing in life, you need to wait.</p>
<blockquote readability="5">
<p>“There’s no such thing as failure – just waiting for success.” – John Osborne</p>
</blockquote>
<p>Like in life, wait in programming is also unavoidable. It is a tool, that you will need some day on desperate situations. For example, a <a href="https://phppot.com/jquery/php-image-slideshow-with-jquery-using-multiple-file-upload/">slider</a>, a fading animation, a <a href="https://phppot.com/jquery/bouncing-ball-animation-using-jquery/">bouncing ball</a>, you never know.</p>
<p>In this tutorial, we will learn about how to wait one second in JavaScript? One second is an example. It could be a “5 seconds” or any duration your code needs to sleep before continuing with operation.</p>
<p>Refer this linked article to learn about <a href="https://phppot.com/php/php-sleep/">PHP sleep</a>.</p>
<p><img loading="lazy" class="alignnone size-large wp-image-19831" src="https://phppot.com/wp-content/uploads/2022/10/wait-550x416.jpg" alt="Wait" width="550" height="416" srcset="https://phppot.com/wp-content/uploads/2022/10/wait-550x416.jpg 550w, https://phppot.com/wp-content/uploads/20...00x227.jpg 300w, https://phppot.com/wp-content/uploads/20...68x580.jpg 768w, https://phppot.com/wp-content/uploads/2022/10/wait.jpg 1100w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>JavaScript wait 1 second</h2>
<p>I have used the good old setTimeout JavaScript function to wait. It sleeps the processing for the milliseconds duration set. Then calls the callback function passed.</p>
<p>You should put the code to execute after wait inside this callback function. As for the wait duration 1000 millisecond is one second. If you want to wait 5 seconds, then pass 5000.</p>
<p>This code will be handy if you are creating a <a href="https://phppot.com/javascript/javascript-news-ticker/">news ticker</a> like scroll animation.</p>
<pre class="prettyprint"><code class="language-javascript"> var testWait = function(milliseconds) { console.log('Before wait'); setTimeout(function() { console.log('After wait'); }, milliseconds); } testWait(1000);
</code></pre>
<h2>JavaScript wait 1 second for promise</h2>
<p>If you are using a modern browser, then you can use the below code. Modern means, your browser should support ES6 JavaScript standard.</p>
<p>In summary, you need support for JavaScript Promise. Here we use the setTimeout function. It resolves the promise after the defined milliseconds wait.</p>
<pre class="prettyprint"><code class="language-javascript">// Promise is available with JavaScript ES6 standard
// Need latest browsers to run it
const wait = async (milliseconds) =&gt; { await new Promise(resolve =&gt; { return setTimeout(resolve, milliseconds) });
}; const testWait = async () =&gt; { console.log('Before wait.'); await wait(1000); console.log('After wait.');
} testWait();
</code></pre>
<h2>JavaScript wait 1 second in loop</h2>
<p>If you want to wait the processing inside a loop in JavaScript, then use the below code. It uses the above Promise function and setTimeout to achieve the wait.</p>
<p>If yours is an old browser then use the first code given above for the wait part. If you need to use this, then remember to read the last section of this tutorial. In particular, if you want to “wait” in a mission critical JavaScript application.</p>
<pre class="prettyprint"><code class="language-javascript">const wait = async (milliseconds) =&gt; { await new Promise(resolve =&gt; { return setTimeout(resolve, milliseconds) });
}; const waitInLoop = async () =&gt; { for (let i = 0; i &lt; 10; i++) { console.log('Waiting ...'); await wait(1000); console.log(i); } console.log("The wait is over.");
} waitInLoop();
</code></pre>
<h2>JavaScript wait 1 second in jQuery</h2>
<p>This is for people out there who wishes to write everything in jQuery. It was one of the greatest frontend JavaScript libraries but nowadays losing popularity. React is the new kid in the block. Here in this wait scenario, there is no need to look for jQuery specific code even if you are in jQuery environment.</p>
<p>Because you will have support for JavaScript. You can use setTimeout without any jQuery specific constructs. I have wrapped setTimeout in a jQuery style code. Its old wine in a new bottle.</p>
<pre class="prettyprint"><code class="language-javascript">// if for some strange reason you want to write // it in jQuery style // just wrapping the setTimout function in jQuery style $.wait = function(callback, milliseconds) { return window.setTimeout(callback, milliseconds); } $.wait(function() { $("#onDiv").slideUp() }, 1000);
</code></pre>
<h2>Cancel before wait for function to finish</h2>
<p>You may have to cancel the wait and re-initiate the setTimeout in special scenarios. In such a situation use the clearTimeout() function as below. Go through the next section to know about such a special wait scenario.</p>
<pre class="prettyprint"><code class="language-javascript">let timeoutId = setTimeout(() =&gt; { // do process }) // store the timeout id and call clearTimeout() function // to clear the already set timeout clearTimeout(timeoutId);
</code></pre>
<h2>Is the wait real?</h2>
<div class data-block="true" data-editor="3h9g4" data-offset-key="730ai-0-0" readability="22.5">
<div class="public-DraftStyleDefault-block public-DraftStyleDefault-ltr" data-offset-key="730ai-0-0" readability="40">
<p>You need to understand what the JavaScript wait means. When the JavaScript engine calls setTimeout, it processes a function. When the function exits, then a timeout with defined milliseconds is set. After that wait, then JavaScript engine makes the callback.</p>
<p>When you want to know the total wait period for next consecutive call. You need to add the time taken by your function to process to the wait duration.</p>
<p>So that is a variable unit. Assume that the function runs for five seconds. And the setTimeout wait duration is one second. Then the actual wait will become six seconds for the next call.</p>
<p>If you want to precise call every five seconds, then you need to define a self adjusting setTimeout timer.</p>
<p>You should account the time taken to process, then reduce the time from the wait milliseconds. Then cancel the current setTimeout. And start new setTimeout with the new calculated time.</p>
<p>That’s going to be tricky. If you are running a mission critical wait call, then that is the way to go.</p>
<p>For example, general UI animations, the above basic implementations will hold good. But you need the self adjusting setTimeout timer for critical time based events.</p>
<p>setInterval will come closer for the above scenario. Any other UI process running in main thread will affect setInterval’s wait period. Then your one second wait may get converted to 5 seconds wait. So, you should define a self adjusting setTimeout wait for mission critical events.</p>
</div>
</div>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/javascript/javascript-wait-1-second/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/10/...avascript/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016