Implementing Time Delay in JavaScript
In certain scenarios, it becomes necessary to add a delay in the execution of a script for user interface enhancements or performance optimization. In this context, we will explore how to introduce a time delay in JavaScript to address a specific use case.
Use Case:
Suppose you have an image toggle functionality where clicking an image switches it to a different image, and when clicked again, it reverts to the original image. To enhance the user experience, you want to incorporate a delay of 1 second before the initial image (img.jpg) reappears after clicking the second image (img_onclick.jpg).
Solution:
The setTimeout() function provides a versatile approach to introduce a delay in JavaScript. Its syntax is:
setTimeout(function, milliseconds)
In this solution, we will utilize setTimeout() to create a delay of 1000 milliseconds (1 second) before reverting to the original image img.jpg. Here's the modified code:
<code class="javascript">$(".trigger").toggle(function () { $(this).addClass("active"); $(".trigger").find('img').prop('src', 'http://localhost:8888/images/img_onclick.jpg'); }, function () { $(this).removeClass("active"); // Added setTimeout to introduce a delay setTimeout(function() { $(".trigger").find('img').prop('src', 'http://localhost:8888/images/img.jpg'); }, 1000); // 1000 milliseconds delay });</code>
By incorporating this change, when the second image (img_onclick.jpg) is clicked, the script will wait for 1 second before displaying the original image (img.jpg), effectively adding a delay as desired.
Note that there are alternative methods to achieve similar results, but for this particular use case, setTimeout() provides a straightforward and efficient solution.
The above is the detailed content of How to Implement a Specified Time Delay in JavaScript for a Specific Use Case?. For more information, please follow other related articles on the PHP Chinese website!