如何使用其他功能停止功能?

时间:2017-04-05 21:06:08

标签: javascript

我正在尝试创建一个函数来停止查找下一张幻灯片,并且还没有给我一条错误消息,指出找不到该资产。

我的文件夹中有6个资源。

避免错误:

  

GET   文件:///Users/ferfas/Desktop/1.33_1024x768/initialFrames/frame_7.jpg   净:: 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 个答案:

答案 0 :(得分: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();