简体   繁体   中英

Multithread JavaScript: Image Slider

I want to make a simple slider for my webpage. Below is the function to load images.

However, it's not running as expected. It's an infinite loop and freeze the webpage. I'm not sure how to fix this but I think that it has to be run on another thread.

What is the best solution for this? Thank you.

function loadProd_logos() {
    var prod_logos = ["prod_01.png", "prod_02.png"];
    var prod_cnt = prod_logos.length;
    var prod_last = prod_cnt - 1;
    for(var i = 0; i < prod_cnt; i++) {
        prod_logos[i] = '<img class="prod_logo" src="prod_thumb/' + prod_logos[i] + '">';
    }

    var x = 0;
    while (1 == 1) {
        var html = prod_logos[x];
        $(".prod_logo").slideUp("slow");
        wait(1000);
        $(".product_thumb").empty();
        $(".product_thumb").append(html);
        $(".prod_logo").slideDown("slow");
        wait(5000);
        x++;
        if(x == prod_last) {
            x = 0;
        }
    }

}

function wait(x) {
    setTimeout(function () {
    }, x);
}

One immediate problem that I see is that wait is assumed to be a blocking function. setTimeout works by firing the provided callback after x milliseconds. If you want to perform a task repeatedly over an interval, use setInterval and perform the operation within the callback you provide.

https://jsfiddle.net/kd4x3uw5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM