How to recover a value within the setTimeout function with jquery?

Asked

Viewed 1,298 times

0

I’m trying to recover a value within the setTimeout function to make a calculation plus the result is totally different than I expected.

var aux = '1.056,00';

//Retiro a formatação da moeda.
aux = aux.replace('.', '');
aux = aux.replace(',', '.');

var vlr_unitario = setTimeout(function(){
    aux;
},10);

alert(vlr_unitario);

Can anyone help me? I want to recover a value that is within the setTimeout function.

var unitario_aux = ($("#valor_unitario").val() === '') ? 0 : $("#valor_unitario").val(); //Retiro a formatação da moeda do valor_unitario. 
unitario_aux = unitario_aux.replace('.', '');
unitario_aux = unitario_aux.replace(',', '.');
var vlr_unitario = 0;
var idTimeOut = setTimeout(function () {
    vlr_unitario = unitario_aux;
    clearTimeout(idTimeOut);
}, 10);
alert(vlr_unitario);
  • You want to assign the value of aux to the vlr_unitario variable?

  • Bruno, why then use setTimeout? if you return it right after the method? Imagine like this, the setTimeout part will only happen after 10 milliseconds, but the next line will already have been executed, hence the logic is wrong.

  • Bruno explains better what you want to do, it can pass for another functionality that the setTimeout.

  • I understand your logic William, but what happens is that this function I am developing, it is very dynamic and there is a currency formatting function (priceFormat) then every time I change the value_unitario field this function is executed and the acronym 'R$' comes along with the value of the wrong calculation. Returns the error: Nan pq the function is trying to make a calculation with string and numbers. got?

  • @Brunoduarte explains what you want to do and shows you the code you already have. You’ll see that the solution to the problem arises and maybe you’ll learn new ways to do it.

  • I want to recover a value that is within the setTimeout.var unitario_aux = ($("#valor_unitario"). val() == '') ? 0 : $("#valor_unitario"). val(); //Remove currency formatting of value_unitario. unitario_aux = unitario_aux.replace('. ', '');
 unitario_aux = unitario_aux.replace(',', '.');
 
 var vlr_unitario = 0;
 var idTimeOut = setTimeout(function(){
 vlr_unitario = unitario_aux;
 clearTimeout(idTimeOut);
 },10);
 Alert(vlr_unitario);

  • And what’s the idea behind setTimeout? why not a callback feature?

  • @Sergio - Analyzing my code I realized the shit I was doing. I already got the bug fixed here. It is that when I change the value_unitario field this function is executed hence the acronym 'R$' that comes from a mask (priceFormat) comes along with the value hence the wrong calculation me. More now I removed this acronym with the replace and it worked perfectly. I thank you for your attention and that of all who opined.

  • 2

    @Brunoduarte No problem, we are all here because we like to solve problems and learn from each other. What I wanted was to be 100% sure that I understood the question and leave an answer with a solution. And for that you need to piece together all the code you have, because without understanding what you want to do it’s hard to help.

Show 4 more comments

2 answers

2

Just set the value of the variable there within the scope of the function.

The return of the setTimeout function is a number, representing the ID value of the timer that was set.

PS.: In your case, as the alert is out, it displays the result before the timeout function runs. Note that in the code below the Alert was inside the code of the function setTimeout

    var aux = '1.056,00';
    
    //Retiro a formatação da moeda.
    aux = aux.replace('.', '');
    aux = aux.replace(',', '.');
    
    var vlr_unitario = 0;

    setTimeout(function(){
        vlr_unitario = aux;          
        alert(vlr_unitario);
    },10);

  

  • 1

    Only setInterval is executed "without stopping", setTimeout is only run once every time you call, clearTimeout is used to "cancel" the setTimeout, for example your code is like this var timer = setTimeout(caller, 10000); it will take ten seconds for the function to be called, if in the fifth second you run clearTimeout(timer); it will not execute the caller.

  • @Guilhermenascimento Feito!

  • Our @Caputo forgive me, now that I understood, I had not realized, can make a rollback in the answer. Forgive the gaffe. Even a positive is worth your answer.

1

The function setTimeout is considered "asynchronous" (remembering the thread of other languages) and so what runs within it is the part of the other events.

But you can access the variable within it, but the other functions can only access after the "timeout" has been completed and the event within it has ended (if there are long "loops").

For more details please read this reply What is the real advantage of using a Callback and what is thread/multithread?

Understanding the access of variables

var vlr_unitario; is a "higher level" variable, for example:

//level global
var variavelglobal;

function A() {
   //superior a todos
   var variavel_acessivel_em_A_B_C;

   var B = function () {
       //infeior a "A", mas superior a "C"
       var variavel_acessivel_em_B_C;

       var C = function () {
           //infeior a A e B
           var variavel_acessivel_em_C;
       };
       C();
   };
   B();
}
  • C can access the variables in B and A
  • B can access the variables in A
  • A can only have access to variables in the "top level"
  • variavelglobal is accessible by all

setTimeout

Having understood this, I will now explain about events with "timeout". These events as setTimeout and setInterval run the part, similar to asynchronous events, when you call:

var test = 0;
setTimeout(function() {
   test += 1; //Soma mais um
}, 1);
alert(test); //Test irá mostrar "zero"

The result is zero as the event was run only after "one millisecond", when it is called alert(test) the variable has not yet received the value and by operating in an "asynchronous" way setTimeout does not stop the process until the setTimeout, how does the sleep in other languages.

Note that in languages such as PHP we have the function called sleep(5);, she is different from setTimeout, when sleep runs like this:

echo '1';
sleep(5);
echo '2';

The process is "locked" until the sleep(...); the 2 will not be shown, ie this is synchronous.

  • Q: It is possible to do "Sleep" in Javascript, but why we do not?
  • R: Why would crash the browser’s "engine" and the window would freeze (for milliseconds or seconds)

This is "one" of the advantages of Javascript, Actionscript and other languages Ecmasript, to be able to work in an "asynchronous" way. See an example "Ajax" is asynchronous, there is "synchronous Ajax", but this is a "bad way".

How to use variable access next to setTimeout

If you have such a code (read the comments within the code):

function main() {
    var variavel = 1;

    //Espera um segundo
    setTimeout(function () {
        variavel += 1;
    }, 1000);

    //Espera dois segundos
    setTimeout(function () {
        //Mostra "2"; pois esperou mais que o tempo do outro setTimeout
        alert(variavel);
    }, 1000);

    //mostra "1" pois não houve espera
    alert(variavel);
}

window.onload = main;

That’s the last one alert did not wait for the setTimeout finish and for this it exhibited 1.

The solution

To be able to use "the solution" you will have to work with "callbacks", to understand read this answer from Stackoverflow, after understanding, read what comes next (only after we understand it even rs):

I suppose the value 1.056,00 comes from a <INPUT> and you want to send him to a <div> (or ajax, or anything else that receives this information), you can perform in this way:

Note: I only used a DIV as an example, you can use for ajax or whatever you need

var elementoInput = document.getElementById("MEU_INPUT");
var elementoDiv = document.getElementById("MEU_DIV");
var botaoTest = document.getElementById("TEST");
var vlr_unitario;

function atualizarDiv() {
   elementoDiv.innerHTML = vlr_unitario;
}

function transformarEmDecimal() {
    var aux = elementoInput.value;//Pega o valor
    
    //Retiro a formatação da moeda.
    aux = aux.replace('.', '');
    aux = aux.replace(',', '.');

    elementoDiv.innerHTML = "Carregando...";
    setTimeout(function(){
        vlr_unitario = aux;

        //Chama a função
        atualizarDiv();
    }, 1000);
}

botaoTest.onclick = transformarEmDecimal;
<input id="MEU_INPUT" type="text" value="1.056,00">
<div id="MEU_DIV">vazio</div>
<input id="TEST" type="button" value="Testar">

  • Hello Guilherme Nascimento? Thanks for your attention! I could understand what you wanted to tell me and it even worked, the function returned the correct value. But only that I need to access externally the value of the variable 'vlr_unitario' that is within the setTimeout function understood? So I can do the calculations. That’s why I put Alert out of function. For me to see how the variable 'vlr_unitario' behaved, but even so you described not working it returns the initial value of the variable that is '0'. Got it?

  • @Brunoduarte yes this is clear, but my answer tells you exactly what you have to do: Is learn to use "callbacks" and work using them, post more of your code for you I see if I can provide you a functional example on it.

Browser other questions tagged

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