简体   繁体   中英

Javascript function only works if alert() is uncommented

I have created a javascript function that calls an array of image urls. After this it iterates through each and changes the src of an image tag every three seconds. The whole function has me a bit stumped. For some reason it only works if I uncomment the alert box.

   alert( index + ": " + value );

At first I thought this may be a sign that the function is working but without the alert it was going too fast for me to see but I added a settimeout and also ran it over instances where some of the images didn't exist just to check if it would log a 404 which it only did with the alert uncommented. This is the full code of the function and it includes the alert.

function displayGalleryImages(pid){

    var images = imageArray[pid]; //array of urls

    jQuery.each(images, function( index, value ) {
         // alert( index + ": " + value );
        setTimeout(function(){  jQuery("#"+pid).attr("src", value)   },3000);
    });
}

I know that there is more to this than a commented alert but I'm struggling to see where I'm going wrong. If anyone can spot a mistake in the code or even a better way of doing any aspect of the function I would really appreciate it.

It is happening because you are using setTimeout() inside loop. when you write alert , browser will wait for your action therefore it works.

Try this:

var len = images.length;
iterate_img(0);
function iterate_img(num){
    setTimeout(function(){
        jQuery("#"+pid).attr("src", value);
        if(num < len-1){
            iterate_img(num+1);
        }        
    },3000);
}

I have used recursive function.

Hope it helps you.

Its because of the scope of value . Its derefered in 3 seconds.

jQuery.proxy is my solution.

You better use:

 function callback(){
   jQuery("#"+this.myPid).attr("src", this.myValue);
 }

 ....
 var callbackThis = {myValue:value, myPid:pid};
 setTimeout(jQuery.proxy(callback, callbackThis),3000);

Therefore callbackThis wraps the values and callback uses callbackThis's values.

try this,

function displayGalleryImages(pid){

    var images = imageArray[pid]; //array of urls

    setAttr(pid,images,0);
}

function setAttr(pid,images,index){
    if(images[index]!=null){
       var value=images[index];
       jQuery("#"+pid).attr("src", value);
       index++;
       setTimeout(function(){   setAttr(pid,images,index);  },3000);
    }
}

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