简体   繁体   中英

JavaScript stop event flow

I am trying to create a slideshow for images. Actually it's more like a fade in and out show.

I could explain the whole thing but I think it's a lot clearer if I just posted my code.

var Images = ["images/1.jpg", "images/2.jpg", "images/3.jpg", "images/4.jpg"]
var ImageContainer = $("#Images");
var Image = $("<img />");
var Counter = 0;

var Animate = {
    Start: function() {
        var that = this;
        Image.attr("src", Images[Counter]);
        ImageContainer.append(Image.fadeIn(that.Middle()));
    },

    Middle: function() {
        var that = this;
        setTimeout(function() {
            that.End();
        }, 2000);
    },

    End: function() {
        var that = this;
        Image.fadeOut(function() {
            Counter = Counter + 1;
            that.Start();
        })
    }
}

Animate.Start();

$("#Button").click(function() {
    //Stop the animation; //Change counter value; //Start animation
});

So my main question is: how do I do the stop, change and start function. My second question is: is this a good way of chaining the events? I tried other ways before but they turn ugly really fast. I also ain't really a JavaScript expert so maybe there is some really weird code in my example. Code like var that = this;makes me think I am doing it wrong.

After reading this you will be able to answer your own question. You can replace var that = this; by using call or apply (there is already a lot of docs and questions about that).

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