function is not defined

0

This code was working without showing me any errors. Then I put a setTimeOut, it keeps working, but it gives a annoying error in the browser log, saying that the function is not defined. I should be putting setTimeOut in the wrong way. Here is 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();
    
asked by anonymous 10.05.2018 / 16:33

1 answer

1

This is showing the error because you are setting the function as a parameter of setTimeout . See:

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

montaAlua();

The correct thing is you 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, the parenthesis is not used, if it is used, the function will be executed immediately.

Or simply:

setTimeout(function montaAlua(){ console.log('Funcionou!'); }, 1000);
    
10.05.2018 / 16:52