setTimeout inside a function [duplicate] - javascript

This question already has answers here:
setTimeout(): If not defined in EcmaScript spec, where can I learn how it works?
(2 answers)
Closed 6 months ago.
function delay2sec(){
let name = "abc"
setTimeout(function () {
name = "xyz"
}, 0)
return name
}
console.log(delay2sec())
The output is abc.
Can someone explain why it is not reassigning the name to 'xyz'?

In order to understand this behavior, you need to understand how the event loop works:
Your setTimeout adds an event to the event loop, which will be executed after the current function. Your return statement is evaluated before the current function ends, so the return evaluates the value before the change.

Related

Explaining anonymous function [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Advanced JavaScript: Why is this function wrapped in parentheses? [duplicate]
(4 answers)
Closed 4 years ago.
Can anybody explain below code? All I know is it is anonymous function but what is (0) doing?
var output = (function(x) {
delete x;
return x;
})(0);
console.log(output);
Why output of above code comes zero. Can anybody explain?
That's because what you're doing is creating a function and then calling it immediately where x = 0. Your function is returning x, and thus 0.
As for what anonymous functions are, they are basically a function that gets stored in a variable. You call it from the variable instead of by name. So, for example:
var output = function (x) { return x;};
Can be called like this:
output(0);
As opposed to the normal way like this:
function myOutput(x) {
return x;
}
myOutput(0);

undefined function when accessed from asynchronous function [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
I don't understand, why when I set a function to an object instance, whenever it is accessed from something asynchronous, like setTimeout or a promise, it is undefined. Can someone please explain? Is there a workaround?
Thanks
function Animal() {
this.check = function () {
writeln(typeof this.test);
}
setTimeout(this.check, 1000); // returns undefined
}
var animal = new Animal();
animal.test = function () {
}
animal.check(); // returns function
Because you're losing context here:
setTimeout(this.check, 1000);
So therefore this inside check will be window, which does not have a test property. Maybe do:
setTimeout(this.check.bind(this), 1000);
Side note: Having dynamically assigned functions is a performance killer and therefore bad style. There's always a better way...

How to handle returning an inner callback variable? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
How do I access a variable inside a callback without reassigning it to a variable first?
For example, the following code works:
let volume = 0;
loudness.getVolume((err, vol) => {
volume = vol;
});
But what if I wanted it to be assignable directly to a const. The following returns undefined:
const volume = loudness.getVolume((err, vol) => vol));
The short answer is you can not. The callback function exists in it's own scope isolated from the rest of the code. The only way to extract that info to be used in the rest of the code is to assign it to a variable that exists in a parent scope.
In simple terms do what you did in your first example.

Javascript function timer. Not working as expected [duplicate]

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 5 years ago.
Problem: Hello i'm a little stuck as to why setTimeout() does not call the function specified after the time passed I've tried a few things but nothing seems to work
Solution: If anyone knows any other way to call a function after a specific time
Here is my code :
refreshStats: function(){
this.goldLabel.text = Math.floor(this.player.data.gold);
this.attackLabel.text = Math.floor(this.player.data.attack);
this.defenseLabel.text = Math.floor(this.player.data.defense);
if (this.player.questsDone.length > 0){
console.log(this.player.questsDone)
this.bpText.text = this.player.questsDone[this.player.questsDone.length-1];
setTimeout(this.FadeConsoleText(), 5000);
}
},
FadeConsoleText: function(){
console.log("log");
},
Current output:
"Quest"
"a"
wanted Solution output:
"Quest"
(wait then call function)
"a"
Thank you in advanced
You want to pass the function, not what the function returns to setTimeout:
setTimeout(this.FadeConsoleText, 5000);

How to return value from anonymous function nested in javascript (node.js) [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I'm having problems trying to add rows to the variable x. I have not understood how to return a value from an anonymous function called by another function.
var pgClient = new pg.Client(connectionString);
pgClient.connect();
var query = pgClient.query("SELECT * from sceglie");
var x = [];
query.on("row", function(row,result){
result.addRow(row);
x.push(row);
});
console.log(x);
There is no way to do what you are trying to do. Javascript is a synchronous language in that it executes line by line. So this line:
console.log(x)
Will execute right away. The "on" function will only execute when it is called, so your log statement will always have the empty value.
Link to good article explaining JS environment

Categories