简体   繁体   中英

Javascript function shows “undefined” in console

I have a grid of images that I want to blink on and off one at a time once through. I had the below code working a few years ago on an old site and wanted to reuse the code but I cannot get it working on the new site.

$('document').ready(function() {

    var myArray = ["img.square1","img.square2","img.square3","img.square4","img.square5","img.square6","img.square7","img.square8","img.square9","img.square10","img.square11","img.square12","img.square13","img.square14","img.square15"];

    console.log(myArray)
    var count = 15;
    function counter() {
        if(count < 16 && count > -1){
            $(myArray[count]).fadeTo(100, 0.1, function(){
                $(myArray[count]).fadeTo(100, 0.7, function(){
                    $(myArray[count]).fadeTo(200, 0.5, function(){
                        $(myArray[count]).fadeTo(500, 1);
                        count--
                console.log(count);
                    });                                      
                });

            });

        }else{
            clearInterval(myInterval);  
            //console.log("interval cleared");
        }
    }
    //counter();
    try{
        counter();
        alert('I guess you do exist');
    }
    catch(e){
            alert('An error has occurred: '+e.message);
    }

    console.log(counter());
    var myInterval = setInterval(counter(), 1100);
});

You can substitute using .queue() and .fadeTo() callback for setInterval()

function counter(selector) {
  return $(selector).queue("images", $.map($(selector), function(image) {
    // `next` is a reference to the next function in `queueName`: `"images"`
    return function(next) { 
      return $(image).fadeTo(100, 0.1, function() {
        $(this).fadeTo(100, 0.7, function() {
          $(this).fadeTo(200, 0.5, function() {
            $(this).fadeTo(500, 1, next);
          });                                      
        });
      });
    }
  })).dequeue("images").promise("images")
}

counter("img[class^=square]")
.then(function() {
  console.log("done", this)
})

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