The issue with the callback function not being triggered within a self-repeating loop

As I work on creating a user-script to incorporate a trailer video into a website, I encountered an issue with the callback function in my script. The goal is to filter the real source of the video from different URL formats, but for some reason, the callback just won't cooperate.

function test_url(preview,list,callback) {
if (list.length) {
    preview.src = list[0][0];
}
preview.onerror = function() {
    if (list.length) {
        test_url(preview,list);   // the function will be re-executed until the passed list is empty
    }
    else {
        console.log('No more url available!');
        if (callback && typeof(callback) === "function") { callback(); }
        else {console.log('callback is : '+ typeof callback);}
        return;
    }
};
if (!list[0].length) {
    list.splice(0,1);
}
else {
    list[0].shift();
}}

test_url(Preview,URLs,function() {console.log('This is a callback.')})

The current problem persists with the callback showing that callback is undefined.

The structure of the list provided looks like this:

[
    ['www.example1.com','www.example2.com'],
    ['www.example3.com','www.example4.com'],
    ['www.example5.com','www.example6.com']
]

As I navigate through this JavaScript challenge as a beginner, I am unsure where the hitch lies. Any insights or guidance would be greatly valued.

Answer №1

Ensure to provide the callback function for execution.

When calling the `test_url` function recursively, remember to include the callback method as the last parameter. Otherwise, when your list becomes empty, there will be no defined callback method.

Take a look at the code snippet below where I have included the callback executions:

function test_url(preview, list, callback) {
if (list.length) {
    preview.src = list[0][0];
}
preview.onerror = function() {
    if (list.length) {
        test_url(preview, list, callback); // include the callback
    } else {
        console.log('No more URLs available!');
        if (callback && typeof(callback) === "function") { 
            callback(); 
        } else {
            console.log('The type of callback is: ' + typeof callback);
        }
        return;
    }
};
if (!list[0].length) {
    list.splice(0, 1);
} else {
    list[0].shift();
}
}

test_url(Preview, URLs, function() {
    console.log('This is a callback.');
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for minimizing the need to copy the entire dojo library each time you create a new Java EE package for deployment on GlassFish

Currently, I am diving into comet programming and utilizing the cometd implementation along with the JavaScript dojo library before deploying my war files to GlassFish. The issue I have encountered is that every time I create a new project, I find myself i ...

Issues arising from utilizing Twitter Bootstrap 3.1.x, the box-sizing property, and Revolution Slider

I'm currently working on a PyroCMS theme that is built with Twitter Bootstrap 3.1.x and includes Revolution Slider. However, I've encountered an issue where the property box-sizing: border-box; creates an unwanted grey border as shown in the imag ...

Initiate a function following a 3-second click on an image

I'm facing a peculiar challenge with my website - I have an invisible button that needs to be pressed for 3 seconds in order to trigger a specific action. Here is what I've attempted so far: $("#basicChn").on({ mousedown: function() { $ ...

Different methods to obscure solely URLs in AngularJS

Is there a way to effectively obfuscate URLs in AngularJS? Currently, I am using base 64 encoding as a method of obscuring my URLs. For example, let's say my URL is: I encode and decode it like this: aHR0cDovLzE5Mi4wLjAuMC9teS91cmwv However, when ...

Tips for effectively handling requestAnimationFrame

I created a unique function that both scrambles and translates text. The functionality is smooth if you patiently wait for the animation to finish before moving the mouse over to other elements. However, if you try to rush through to the next one, the prev ...

Positioning a designated div directly above a designated spot on the canvas

I'm grappling with a challenge in my game where the canvas handles most of the animation, but the timer for the game resides outside the canvas in a separate div. I've been struggling to center the timer around the same focal point as the squares ...

Retrieving information using getStaticProps

I'm currently working on a new function that pulls data from The Guardian API, but I've hit a roadblock with an error message. Below is the response that's being returned: Furthermore, presented here is the code snippet for the asynchronous ...

jQuery shorthand conditional statements

I currently have a jQuery function that is triggered by two separate buttons. $("#btnSearch, #btnDirectorSearch").click(function () { The construction of the HTML output within this function relies on which button was clicked. To accomplish this, I am ut ...

How can we prevent users from changing URLs or accessing pages directly in Angular 7 without using authguard?

Hey there! I am trying to find a way to prevent users from accessing different pages by changing the URL, like in this scenario. Is there a method that can redirect the user back to the same page without using Authguard or any Modules? I have a StackBlit ...

Activate trust proxy in Next.js

When working with Express.js, the following code snippet enables trust in proxies: // see https://expressjs.com/en/guide/behind-proxies.html app.set('trust proxy', 1); I am attempting to implement a ratelimit using an Express middleware that is ...

What is the impact of memory on NodeJS performance?

Currently delving into a book on NodeJS, I stumbled upon an intriguing example: const express = require('express') const bodyParser = require('body-parser') const app = express() var tweets = [] app.listen('8000', '172 ...

Can one retrieve an express session using the sessionID given?

I have a NodeJS Express application with express-session that works well, however, it needs to be compatible with a cookie-less PhoneGap app. My question is: Can I access the data in an express session using the sessionID? I was thinking of adding the se ...

Discovering the meeting point where two dives converge

Is there a method to change the color of the overlapped common part of two animated circles? ...

The issue of VueRouter malfunctioning in history mode within Wordpress

I have integrated Vue into my Wordpress theme, but I am facing an issue with the router when setting mode: 'history'. The site goes blank and even after trying to configure the .htaccess file, nothing seems to work. My project is located in the V ...

Struggling to find the width of an SVG text box or add line breaks after a specific number of characters?

I am currently working on creating an SVG text box using the amazing Raphael library. The content inside this text box comes from a dynamic string that is extracted from an XML document. There are times when this string turns out to be longer than the can ...

What is causing the lack of updated data on the components when navigating to a different page? (Vue.JS 2)

I am working with 2 components The first component looks like this : http://pastebin.com/M8Q3au0B Due to the long code, I have used pastebin for it The first component calls the second component The second component is as follows: <template> ...

Tips for successfully sending a nested function to an HTML button and dropdown menu

I'm working on two main functions - getChart() and fetchData(). The goal is to retrieve chart data and x/y axes information from a database. Within the getChart function, I'd like to incorporate a dropdown menu for displaying different types of c ...

Utilizing a particular iteration of npm shrinkwrap for project dependencies

When deploying my node.js app to Appfog, I encountered a problem with their install script failing to parse npm-shrinkwrap.json. The current format of a dependency in shrinkwrap.json is as follows: "async": { "version": "0.2.10", "from": " ...

Is it possible for AJAX and PHP to collaborate seamlessly?

Currently, I'm facing an issue where my Js file is failing to recognize a php variable that is generated by ajax. Let's take a look at the structure: index.php: <script src="js.js"> </script> <? include('build.php'); &l ...

Using Angular to pass parameters to a function

When passing a parameter to the getActiveId function in the ng-click <span class="col ion-ios7-heart-outline center" ng- click="getActiveId({{activeSlide.selected}})"> The value turns to zero in the controller, but it is passed correctly after tes ...