function is not defined

Asked

Viewed 306 times

0

This code was working without showing me any errors. Then I put a setTimeOut, it keeps working, but gives a boring error in the browser log, saying that the function is not set. I must be putting setTimeOut wrong. Here’s the code:

 setTimeout(function montaAlua(){


      let montarAula = {

        idUsuario: document.querySelector('#id').textContent,
        token: document.querySelector('#token').textContent,
        id: document.querySelector('#ultima-aula').textContent
      };

      var xhr = new XMLHttpRequest();
      var variavel = document.querySelector('#token-servico').innerHTML;

     xhr.open("POST", "http://54.233.209.248:8080/nuite- 
  web/rest/courses/findById", true);
      xhr.setRequestHeader("Content-type", "application/json");
      xhr.setRequestHeader("Authorization", "Bearer " + variavel);
      xhr.addEventListener("load", function(){

        if(xhr.status == 200){


          let curso = xhr.responseText;
          curso = JSON.parse(curso);

          let video = '';
          video += curso.video;
          document.querySelector('#video').innerHTML = video;

          let descricao ='';
          descricao += curso.descricao;
          document.querySelector('#curso-descricao').innerHTML = descricao;

        }
      });
      xhr.send(JSON.stringify(montarAula));
    }, 1000 );

montaAlua();
  • 1

    You can put the error image in the browser.

  • Careful, it seems your function name is wrong: montaAlua(). Shouldn’t be montaAula() ?

  • Yes.. is wrong, but it is not the name of the function. They match on the first and last line

1 answer

1


This shows the error because you are setting the function as the setTimeout. Behold:

setTimeout(function montaAlua(){ console.log('Funcionou!'); }, 1000);

montaAlua();

The correct thing is to define the function and pass it as a parameter in the method setTimeout

function montaAlua() {
  console.log('Funcionou!');
}

setTimeout(montaAlua, 1000);

Note when passing function as parameter, parentheses are not used, if used, the function will be executed immediately.

Or simply:

setTimeout(function montaAlua(){ console.log('Funcionou!'); }, 1000);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.