使用Javascript进行图像动画

Why the timeout don't work? If i work without the function sleep, they return to me an undefined data.. With this function they work but without sleeping time, they go directly to the last image.. :-/

    function sleep(value, data, i) {
        document.getElementById(value).src = data[i];
    }

function imgAnimation(value){
    var img = document.getElementById(value).src;
    $.ajax({
    type: "POST",
    url: "static/cercaThumbs.php",
    data: 'id=' + value,
    datatype: 'json',
    success: function (data) {
        var elements = Object.keys(data).length;
        for (var i = 0; i < elements; i++) {
                if(i == elements){i = 0;}
                setTimeout(sleep(value, data, i), 300);
        }
    }
});
}

You need to pass a function to setTimeout. You're calling the function sleep and passing its result.

setTimeout(function() {
  sleep(value, data, i);
}, 300);

But it still won't work, because you're setting a bunch of timeouts at the same time, so they'll all trigger 300ms later at the same time. To animate you might try something like:

var data = [
  'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0030.png',
  'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0031.png',
  'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0032.png',
]
var frame = 0;
var elements = data.length;
var animation = setInterval(function() {
  frame = (frame + 1) % elements;
  document.getElementById('test').src = data[frame];
}, 300);
<img id=test>

This sets up a single repeating callback which can advance to the next frame each time. In the example above it will loop forever, or you can call clearInterval(animation) once you're finished.

</div>

Ok, with the help of Nick, this is the correct code:

function imgAnimation(value){
    $.ajax({
    type: "POST",
    url: "static/cercaThumbs.php",
    data: 'id=' + value,
    datatype: 'json',
    success: function (data) {
        var elements = Object.keys(data).length;
        var frame = 0;
        var animation = setInterval(function() {
        frame = (frame + 1) % elements;
        document.getElementById(value).src = data[frame];
        }, 500);
        document.getElementById(value).addEventListener("mouseout", function(){
            clearInterval(animation);
            document.getElementById(value).src = data['0'];
        });
    }
    });
}