2017-04-05 83 views
0

我正在嘗試創建一個函數來停止查找下一張幻燈片,並且也不會給我一條錯誤消息,指出找不到資產。如何用其他功能停止功能?

我在我的文件夾中有6個資產。

避免錯誤:

GET file:///Users/ferfas/Desktop/1.33_1024x768/initialFrames/frame_7.jpg net::ERR_FILE_NOT_FOUND

代碼:

var pictureIndex = 1; 
var baseUrl = "initialFrames/"; 
var image_url = undefined; 
var timer = setInterval(next, 2500); 

var newImage = new Image(); 
newImage.onload = imageFound; 
newImage.onerror = imageNotFound; 

function next() 
{ 
image_url = baseUrl + 'frame_' + pictureIndex + '.jpg'; 
tryLoadImage(image_url); 
} 

function tryLoadImage(url) { 
newImage.src=url; 
} 

function imageFound() { 
document.getElementById("backInit").src = image_url; 
pictureIndex++; 
} 

function imageNotFound() { 

// perform some function to stop calling next() 
clearInterval(timer); 
} 

回答

1

爲什麼要使用setInterval的呢?

您可以反覆加載圖片:

var pictureIndex = 1; 
var baseUrl = "initialFrames/"; 
var image_url = undefined; 

var newImage = new Image(); 
newImage.onload = imageFound; 
newImage.onerror = imageNotFound; 

function next() 
{ 
    image_url = baseUrl + 'frame_' + pictureIndex + '.jpg'; 
    tryLoadImage(image_url); 
} 

function tryLoadImage(url) { 
    newImage.src=url; 
} 

function imageFound() { 
    document.getElementById("backInit").src = image_url; 
    pictureIndex++; 
    //you can check here if the pictureIndex image exists, and then only call next if it exists 
    // if (imageExists()) { 
    next(); 
    // } 
} 

function imageNotFound() { 
    console.log('done loading images...'); 
} 

next();