What is the proper sequence for executing a JavaScript function?

What task am I attempting to accomplish?
I am trying to run two functions sequentially in JavaScript, but it seems that both functions are being called and executed simultaneously.

What seems to be the issue?
The setModalBox function throws an undefined error when called before the setProjects function.

What have I already attempted as a solution?
I have tried using Promise with setTimeout, which works sometimes. However, there are still instances where the setModalBox function is called first and causes the same error.

Snippet of JavaScript code:

class Portfolio{
  init() {
    this.setProjects();
  }

  // Rest of the JavaScript code...
}

// HTML code...

HTML:

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Projetos - Vitor Hugo's Portifolio</title>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>
  </head>

  <body>
    <header>
      <div id="wrapperJS" style="position: relative; overflow: hidden">
      <nav>
        <a class="logo" href="/">Vitor Hugo</a>
        <div class="mobile-menu">
          <div class="line-1"></div>
          <div class="line-2"></div>
          <div class="line-3"></div>
        </div>
          <ul class="nav-list">
            <li><a href="index.html">Home</a></li>
            <li><a href="sobre.html">Sobre</a></li>
            <li><a href="projetos.html">Projetos</a></li>
            <li><a href="contatos.html">Contato</a></li>
          </ul>
        </nav>
      </div>
    </header>
    
    <!-- Other sections of HTML... -->

  </body>
</html>

I need guidance on how to resolve this issue. If more information is required, please let me know. My apologies for any spelling or grammar errors, as I am currently learning English.

Answer №1

Consider utilizing async/await for more efficient code execution. Here's an example of how you can implement it:

const fetchData = async () => {
try {
await // Your code goes here
}catch (error){
console.log(error)
}
};

Afterwards :

fetchData().then(updateUI());

By doing this, your functions will run sequentially.

Answer №2

Simply invoke setModalBox towards the conclusion of the DOMContentLoaded event handler.

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

What is the purpose of using defer="defer" in JavaScript?

I've been experimenting with Three.js and found that it only functions properly when used like this: <script src="script.js" defer="defer"></script> However, I'm puzzled as to why the defer="defer" attribute is crucial... Can anyon ...

Is it possible to implement cross-domain login with Passport.js?

Is it possible for a user to log in from a different domain? For example, the main site has a login form that uses AJAX to post to a route on my Node.js server. // Submit form to Node server FROM WEBSITE $('#submit-project-form').submit(function ...

Exploring the Vertical Metrics of Various Typeface Styles

I'm encountering a problem and struggling to find a solution. I'm in the process of creating a website and incorporating various fonts. My goal is to ensure that every font appears visually similar to the others and align perfectly at the base. ...

Enhance Your YouTube Comment Section with CSS Styling

I am brand new to css html and I'm attempting to create a comment display system similar to that of YouTube using only CSS. My goal is to have an image of the commenter displayed, followed by their username and comment text listed beside it. So far, I ...

calling requestAnimationFrame from within a freshly created instance

I'm encountering an issue with executing an animation. Specifically, this problem arises within var ob1 = function() {};. Once triggered, the animation runs for a brief period before I receive the error message Uncaught RangeError: Maximum call stack ...

What is the best way to display multiple HTML files using node.js?

click here to see the image Here is my server.js file. Using express, I have successfully rendered the list.html and css files on my server. However, I am encountering an issue when trying to navigate from list.html to other html files by entering localho ...

Is it possible for me to customize the CSS of the masterpage for a specific aspx file?

Recently, I completed a website that was almost ready to be published. However, my client now wants to add a new page with similar content as the main masterpage (including the logo, menu, and a few buttons), but with some changes in colors and background ...

In HTML, specify that the height of both the `html` and

I am facing an issue with the container-about div. I have set its height to 100% so that the div occupies the entire width and height after the header div. The problem is that currently, I cannot scroll to view the full text. It would be great if there wa ...

Stop the http requests in Angular as the user continually types in the autocomplete input field

Currently, I have an input field that utilizes a material autocomplete component. This component makes calls to the server for results as the user types. While it is working correctly for now with the server returning results in order, I am looking for a ...

Alter color upon click using jQuery

I am facing an issue with my code where I want to make it so that when a user clicks on one of the glyphs on the side of the page, elements with ids starting with the same letter will remain black while everything else, including other glyphs, turn grey. ...

JS backbone require global models in js

I am looking to implement a UserSession model that will handle loading and saving session IDs into cookies using the jQuery cookie plugin. Below is the code for my UserSession model module: define(['jQuery', 'Underscore', 'Backbo ...

Ways to fetch additional Product Cards using JSON and a nextPage parameter

I'm facing difficulties in nesting a fetch inside another fetch. I'm not sure if this is the correct approach, but my goal is to utilize Vanilla JavaScript to fetch another JSON from the nextPage URL within the JSON list when the "load more" butt ...

How to prevent selecting future dates in Material UI date picker

Is there a way to prevent selecting future dates in the material UI datepicker? I noticed that it doesn't seem to have any prop options like disableFuture or past. For those interested, here's the link to the github repository sandboxlink ...

Troubleshooting issues with custom-switch in jquery.repeater with bootstrap

Hey there! I'm having an issue with the jquery form repeater plugin and bootstrap combination. Specifically, I have a form element that is part of the repeater form: <div class="custom-control custom-switch"> <input typ ...

Interactive bar chart that updates in real-time using a combination of javascript, html, and

Current Situation: I am currently in the process of iterating through a machine learning model and dynamically updating my "divs" as text labels. My goal is to transform these values into individual bars that visually represent the values instead of just d ...

Interact with a JSON API using JavaScript by incorporating dynamic user input

Recently, I delved into tutorials on utilizing JSON data and JavaScript. Feeling inspired, I decided to create a simple app using an API. However, I encountered a hurdle and I'm struggling to identify its cause. The problem seems to be related to how ...

Exploring the process of transferring a variable from Frontend to Backend via a GET API in ReactJS with an Express API

When working with my freight Shipment table, I need to access the email of the logged-in user in order to perform some frontend tasks. However, I am struggling to retrieve this information using the Axios.get() method and use it to query my MySQL DB. In t ...

Finding the number of parameters in an anonymous function while using strict mode can be achieved through which method?

Is it possible to determine the arity of a function, such as the methods.myfunc function, when using apply() to define the scope of this and applying arguments? Following the jQuery plugin pattern, how can this be achieved? (function($, window, document ){ ...

Using Material-UI with ReactJS: Implementing color alternation in Material-UI <Table/>'s <TableRow/>

I am currently utilizing Material-UI's <Table/> component and I would like to alternate row colors between blue and purple. The first row will be blue, the second row will be purple, and so on for every additional row added. How can I dynamical ...

What are some creative ways to customize v-slot:cell templates?

Currently, I have the following code snippet within a table: <template v-slot:cell(checkbox)="row" style="border-left='5px dotted blue'"> <input type="checkbox" v-model="row.rowSelected" @input="toggleS ...