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 incorporating css styles and javascript into handlebar files

I've been trying to figure out how to add styles and js to my handlebar files, but I'm hitting a roadblock. I attempted to use partials to store the stylesheet tags and then include those partials in the handlebars file, but it didn't work a ...

Delaying consecutive calls to query on mouse enter event in React

Currently, I have a React component from antd that utilizes the onMouseEnter prop to make an API query. The issue arises when users hover over the component multiple times in quick succession, which floods the network with unnecessary API calls. To prevent ...

Runtime.UnhandledPromiseRejection - Oops! Looks like we're trying to read properties of something that doesn't exist (specifically 'headers')

I'm facing an unexpected error that has left me puzzled. Let me walk you through what I am trying to accomplish: The task at hand involves fetching data from one API and then transmitting it to another. This process is executed as a background-funct ...

Incorporate a class into the fixed navigation menu using fullpage.js

I am attempting to modify the behavior of a sticky menu as the user scrolls down using fullpage.js. My goal is to have the #top-wrapper behave normally when the first section/page loads, and then add a class of is-fixed as you scroll down. When scrolling ...

"Ng-repeat function seems to be malfunctioning, although I am able to view

There seems to be an issue with ng-repeat when dealing with an array of objects: dummy.json [ {"name":"alpha", "data":[{"name":"Unit 1", "prereqs":[]}]}, {"name":"beta", "data":[{"name":"Unit 1", "prereqs":[]}]} ] While I am able to fetch the total ...

Issue with Semantic-UI Special PopUp not displaying on screen

I'm currently working on creating a unique pop-up feature using custom HTML, with the intention of adding content to it later on. My console is displaying the following message: Popup: No visible position could be found for the popup. $(document) ...

How can the data controller of a model be accessed within a directive that has been defined with "this"?

I'm struggling with accessing data using a directive, especially when I have defined my models like this: vm = this; vm.myModel = "hello"; Here is an example of my directive: function mySelectedAccount(){ return { restrict: 'A&ap ...

Typing the url in the address bar when using Angular's ui-router

Two distinct states are present: .state('test', { url: '/test', templateUrl: 'js/angular/views/test.html', controller: 'UserController', }) .state('test.list', { url: ' ...

Extracting information from dynamically generated tables using Python 2.7, Beautiful Soup, and Selenium

I am in need of assistance with scraping a JavaScript generated table and saving specific data to a csv file. The tools available to me are limited to python 2.7, Beautiful Soup, and/or Selenium. Although I have referred to the code provided in question 14 ...

store the id of each li element dynamically into an array

In my code, a list is generated dynamically and each list item has a special id. I am trying to store each li "id" in one array. This is JavaScript code: var i = 0; $("ul#portfolio li").each(function(eval) { var idd = new Array(); idd[i] = $(this ...

Controller is not being triggered by Ajax method when there is a decimal value

I am currently working on implementing a time registration feature in my web application. Users can select the project they worked on and enter the number of hours spent on that project. Everything is functioning properly until users start adding half-hou ...

Automatically populate the article number field once the article name has been entered

I am currently working on a HTML <form> using PHP. Within this form, there are three <input> fields. The goal is to have the second <input> field automatically populate once the first one is filled out. This will involve triggering an HTT ...

The time.js library is providing inaccurate second values for the given date and time

Utilizing the moment.js library along with the Timezone and BusinessDays extensions in Vue.js, I am developing a datetime format for storing in a MySQL database. Here is the code snippet: import moment from 'moment-timezone' ...

Tips for displaying the Material UI Menu component on the left side instead of the default right side

Recently, I created a dropdown component using Material UI's Menu component. However, the default behavior of the menu is to open towards the right side. I actually need it to open towards the left instead. I attempted to modify its styling, and whil ...

NodeJS loop issue with variable scoping in the context of express and mongoose

My Tech Stack: NodeJS, express, mongoose var i; for(i = 0; i < results.length; i++){ console.log("out: "+i); RegionData.findOne({'rid': results[i].region_id}, function (err, product) { if (product) { console.log("i ...

Generating a new array and merging different sets of keys together

Is there a way to modify how items are added to a jQuery array? Here is the current code snippet in use: var sub_updated = []; $('.current-sub-items').each(function() { $(this).find('.prod-select').each(function() { if ($(th ...

Can anyone tell me where to find the unminified version of Bootstrap 3's docs.min.js file?

Could someone please provide me with the original version of this file? I've been trying to search for it in the project but haven't had any luck. You can find it here: https://github.com/twbs/bootstrap/blob/master/docs/assets/js/docs.min.js. ...

The React hamburger menu triggers a re-render of child elements within the layout

I am currently working with React and Material UI v5. Within my layout, I have a menu component with children. Whenever I click on the menu, it triggers a refresh of the children components. I attempted to resolve this by encapsulating the child components ...

Reset functionality for input selector is malfunctioning

My HTML code looks like this: <input type="number"> <br> <input type="number"> <br> <input type="number"> <br> <button>+</button> In my JS script, I have the following: $('input').on('c ...

Parsing error: 'Unexpected token' found in JSON while attempting to access an external file

Currently working on implementing backbone for a new project along with underscore, requirejs, jquery, and bootstrap. Things are progressing smoothly as I aim to include static survey question data into one of the data models. { "defaultOptions": { ...