user7582130
user7582130

Reputation:

How to stop a function with another function?

I am trying to create a function to stop looking for the next slide and also to not give me a error message that the asset is not found.

I have 6 assets in my folder.

Avoiding error:

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

Code:

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);
} 

Upvotes: 0

Views: 51

Answers (1)

Diogo Sgrillo
Diogo Sgrillo

Reputation: 2701

Why use setInterval at all?

You can load the images iteratively:

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();

Upvotes: 1

Related Questions