As a web developer, it's often necessary to incorporate time delays into your code for various purposes. One such scenario involves switching between images on your website, where you want a delay between clicks to prevent rapid image cycling.
In this specific case, you aim to implement a delay of 1000ms (1 second) after clicking an image to showcase img_onclick.jpg, followed by a delay before reverting back to img.jpg upon a second click. To achieve this, consider using JavaScript's setTimeout() function.
Solution Using setTimeout()
<code class="javascript">var delayInMilliseconds = 1000; //1 second $(".trigger").click(function () { $(this).next(".toggle-container").slideToggle(); // Schedule a callback to switch back to img.jpg after 1 second setTimeout(function() { $(".trigger").find('img').prop('src', 'http://localhost:8888/images/img.jpg'); }, delayInMilliseconds); });</code>
In this solution, we utilize setTimeout() to schedule a callback function that switches back to img.jpg after a delay of 1000ms.
Alternative Solution Without setTimeout()
While setTimeout() is a common approach, it's worth mentioning that there is another solution that involves using the JavaScript Event Loop and an async/await construct. However, this approach is more complex and falls outside the scope of this discussion. For reference, you can find more information on this alternative in the provided question under the "If you want to do it without setTimeout" section.
The above is the detailed content of How to Create Time Delays in JavaScript for Image Cycling: A Practical Example. For more information, please follow other related articles on the PHP Chinese website!