如何停止Ajax映像加载调用新函数



我正在做这样的事情->

$("<img>").attr("src", "path/to/image.jpg").load(function(){
    $("#thediv").append(this);
});

所以我可以在图像完全加载时附加新图像

我有一个定时器,每6秒用新参数调用一次这个函数。。。。但我想调用一个函数来加载一组新的图像,但我有一个在后台运行的旧图像集(异步),我需要停止加载,这样图像就不会附加,因为我不想要那个图像,我正在尝试加载一组全新的不同图像。。。我在想:

function loadNewSet(){
   window.stop(); // i don't quite know if this exist or works but 
                 //should stop all ajax request taking place at that time
   loadImages(); // call some function to load the new set
}

/*//*///*/>/*//*///*//*///*/

更具体地说:

我有一个名为thediv的div,我将在其中放置我的图像

然后我有一组图像或阵列

set1 = ['img1','img2','img3']

set2 = ['img4','img5','img6']

并且我在上设置了thetimer

$(document).ready(function(){
    thetimer=setTimeout("nextSlide()",6000);
});

那么我有nextSlide()

function nextSlide(){
     //this is where i load the next image on the active set (set 1 or set 2)
    img.load(function(){
       thetimer=setTimeout("nextSlide()",6000); // and then i set the timer again
    });
}

但是当调用nextSlide()函数时,它在加载新图像时就像是空闲的,加载后它会在load()上做它应该做的事情,但加载时我调用这个函数loadNewSet()

function loadNewSet(set){
    clearTimeout(thetimer);
    //this is wheere i want to stop any image loading called by any other function
    stopAllImagesLoading();//example
    //then change activeset
    activeSet=set; // set1 or set2
    nextSlide();
}

不太知道我做这件事的方式是否正确,可能是我无法用我现在的方式放下这里的进度。

感谢您的回复。

您可以使用setTimeout生成"工作进程"。

var proc;
somefunc();
function somefunc() {
    //do stuff
    proc = setTimeout(somefunc, 6000);
}
//...
clearTimeout(proc); //Cancel the looping somefunc from executing.

如果不追加,而是执行…之类的操作,会怎么样。。。。

<div id="myDiv">
    <img id="myImg" style="display: none">
</div>

function loadImg(url){
    $("#myImg").attr("src", url).load(function(){
        if(url == $(this).attr(url)){
            // The currently requested image has loaded.  Show it.
            $(this).show();
        }
        else{
            // Finished loading an image that we don't need anymore.  Do nothing.
        }
    });
}

所以如果你打电话给:

loadImg("a.jpg");
loadImg("b.jpg");

.jpg可能会先完成,也可能不会先完成,但这并不重要,因为一旦.jpg完成,什么都不会发生。

尝试使用全局变量来打开或关闭计时器。例如(仅限伪代码):

var gKeepRunning = true;   //KEY TO ANSWER HERE
myRepeatingImageLoader();   //this is the method that will repeat
function myRepeatingImageLoader(){
  $("<img>").attr("src", "path/to/image.jpg").load(function(){
    $("#thediv").append(this);
  });
  if( gKeepRunning == true )   //KEY TO ANSWER HERE - WILL STOP WHEN SET TO FALSE
    var junk = setTimeout('myRepeatingImageLoader();', 6000);   //Repeat again
}
function loadNewSet(){
  gKeepRunning == false;   //KEY TO ANSWER HERE
  loadImages();
}

在此处找到anwser:Javascript:取消/停止图像请求

    if(window.stop !== undefined)
    {
         window.stop();
    }
    else if(document.execCommand !== undefined)
    {
         document.execCommand("Stop", false);
    }

最新更新