Home > Web Front-end > JS Tutorial > How to Implement a Specified Time Delay in JavaScript for a Specific Use Case?

How to Implement a Specified Time Delay in JavaScript for a Specific Use Case?

Susan Sarandon
Release: 2024-10-19 16:12:02
Original
635 people have browsed it

How to Implement a Specified Time Delay in JavaScript for a Specific Use Case?

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)
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template