Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
How running JavaScript function in order?

What am I doing?
I'm try running two function in order but JavaScript is calling and running two function in same time.

What's the problem?
The setModalBox function give undefined error if is called before setProjects function.

What have I already tried?
I tried used Promise with setTimeout it work, but can sometimes setModalBox function be called before and give of same error.

Part of JavaScript:

class Portifolio{
  init() {
    this.setProjects();
    // this.setModalBox();
  }

  setProjects() {
    let response_promise = fetch("contents/projects.json")

    document.addEventListener("DOMContentLoaded", function() {
      response_promise.then(response => response.json().then(projects => {
        // ? Gradient in border for each color language

        for(let project in projects){
          // Div project
          var div = document.createElement("div");
          div.className = "project";
          div.id = `project-${projects[project].name}`
          document.querySelector(".projects").appendChild(div);

          // Tittle project
          var h1 = document.createElement("h1");
          h1.className = "tittle-project";
          h1.innerHTML = projects[project].name;
          document.querySelector(`#project-${projects[project].name}`).appendChild(h1);

          // Paragraph project
          var p = document.createElement("p");
          p.className = "about-project";
          p.innerHTML = projects[project].about;
          document.querySelector(`#project-${projects[project].name}`).appendChild(p);
        }
      }))
    }, false)

    return new Promise((resolve, reject)=>{
      setTimeout(()=>{
        this.setModalBox()
      }, Math.random() * 2000)
    })
  };

  setModalBox(){
    let projectsLength = document.querySelectorAll(".projects")[0].children.length;
    let modalBox = this.modalBox;

    for(let i = 0; i <= projectsLength; i++){
      let projectsAll = document.querySelectorAll(".projects")[0].children[i];

      // That "try" is for not to show error in console
      try{
        // Open Modal Box
        projectsAll.onclick = function(){
          modalBox.style.display = "block"
        };
      }catch{}

      // Close Modal Box, when click at "X"
      this.modalBoxClose.onclick = function(){
        modalBox.style.display = "None"
      };

      // Close Modal Box, when click out of Modal Box
      window.onclick = function(){
        if(event.target == modalBox){
          modalBox.style.display = "None"
        }
      }

      // Close Modal Box, when press esc key
      document.addEventListener("keydown", function(event){
        if(event.key == "Escape"){
          modalBox.style.display = "None"
        }
      })
    }
  }
}

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>
    <script src="mobile-screen.js"></script>

    <!-- Boxes -->
    <div class="projects"></div>

    <!-- Modal Boxes -->
    <div class="modal-box">
      <div class="modal-box-contents">
        <span class="modal-box-close">&times;</span>
        <p>test</p>
      </div>
    </div>
  </body>
</html>

What I have to do? please help me. If need more information,ask. And sorry for any error orthography and grammar I am studing English.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Try async/await. For example you can do it like this:

const setProjects = async () => {
try {
await // Put your code here
}catch (err){
console.log(err)
}
};

Then :

setProjects().then(setModalBox());

Now your functions will be executed in an order.

over 4 years ago · Santiago Trujillo Report

0

You can just call setModalBox at the end of the DOMContentLoaded event handler.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!