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">
You want to assign the value of aux to the vlr_unitario variable?
– Laerte
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.
– Caputo
Bruno explains better what you want to do, it can pass for another functionality that the
setTimeout
.– Sergio
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?
– Bruno Duarte
@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.
– Sergio
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);
– Bruno Duarte
And what’s the idea behind
setTimeout
? why not a callback feature?– Sergio
@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.
– Bruno Duarte
@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.
– Sergio