[英]How to stop Ajax image load calling a new function?
我正在做這樣的事情->
$("<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.
這應該可以幫助您: 使用jquery使用javascript殺死ajax請求。
只需將所有請求保存在一個數組中即可。 當您要停止所有它們時,遍歷它們並.abort()
對它們調用.abort()
。
如果您執行類似...而不是追加操作,該怎么辦?
<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");
a.jpg可能會先完成,也可能不會先完成,但這並不重要,因為一旦a.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();
}
在此處找到答案: Javascript:取消/停止圖像請求
if(window.stop !== undefined)
{
window.stop();
}
else if(document.execCommand !== undefined)
{
document.execCommand("Stop", false);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.