Home > Web Front-end > JS Tutorial > body text

How to Create Time Delays in JavaScript for Image Cycling: A Practical Example

Barbara Streisand
Release: 2024-10-19 16:12:30
Original
808 people have browsed it

How to Create Time Delays in JavaScript for Image Cycling: A Practical Example

How to Implement Time Delays in JavaScript

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!