Behaviour of setTimeout Inside console.log [duplicate] - javascript

This question already has answers here:
setInterval/setTimeout return value
(6 answers)
Closed 5 years ago.
I am executing the following code snippet on browser console.
console.log(
setTimeout(function(){
console.log('a');
},200));
This gives me two outputs. First output is a random number(that is what i thought) and second is a. While I understand that the second output is normal, what is the first random number that is being generated in console.

The other number that is being logged is the return value of setTimeout function, which is the id for the timer, which can be used to clear the timer. See this for details

From MDN:
The returned timeoutID is a numeric, non-zero value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Return_value
The 8 you are seeing is the return value of the call to setTimeout, which is passed to console.log and output.

Related

JavaScript function execution time [duplicate]

This question already has answers here:
Why does a setTimeout delay of 0 still run after all other synchronous code in a for loop? [duplicate]
(2 answers)
Closed 1 year ago.
I wanted to test the execution time of console.log, but whatever number I set as the delay for setTimeout, it is still executed after console.log. I don't understand why so.
function first() {
console.log("This should be printed first");
}
setTimeout(first, 0.00001);
console.log("This should be printed second");
From MDN:
delay Optional The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. Note that in either case, the actual delay may be longer than intended; see Reasons for delays longer than specified below.
No matter how small the delay, the first function is going to be put on a queue and not looked at until the current event cycle (which is in the middle of running the current function) has finished (which won't be until after the last console.log statement has been executed).
Further reading:
Concurrency model and the event loop
JavaScript Event Loop

JavaScript Function Syntax + setTimeout() 'ERR_INVALID_CALLBACK: Callback must be a function. Received undefined [duplicate]

This question already has answers here:
When do I use parentheses and when do I not?
(5 answers)
Closed 1 year ago.
const sayHello = function () {
console.log("hello");
};
sayHello;
sayHello();
setTimeout(sayHello, 1000);
setTimeout(sayHello(), 1000);
I'm a little confused as to why line 5 'does nothing' but also doesn't throw an error, whereas line 8 runs as expected but line 9 throws the invalid callback error. I'm running this code is Visual Studio Code if it makes a difference.
When you use () after a function name, you're executing the function. But without it, you're referencing the function instead. That is why line 5 doesn't do anything. The function is not being executed. But line 6 on the other hand is executing the function, which should print "hello" to the console.
The setTimeout needs a function reference (the callback function), to let it know what to execute after the 1000 ms has passed.
So typing setTimeout(sayHello(), 1000) executes the sayHello function directly instead of providing it as a callback. So that will not work as you intend.
Typing setTimeout(sayHello, 1000), you're instead providing the function reference instead, to the setTimeout will know what function to execute after the 1000 ms has passed. This is the correct way to do it.

Why does this `do`–`while` loop repeat the last value after the end? [duplicate]

This question already has answers here:
Javascript while loop return value
(3 answers)
In Javascript While loop repeats last number when counting from 1 to 5 when run on console [duplicate]
(2 answers)
Closed 4 years ago.
I tried the following code in the Google Chrome console and I’m getting this output. Why is there an additional 4 printed?
var i = 0;
do{
console.log(i);
i++;
} while(i < 5);
Output:
0
1
2
3
4
4
There is no extra 4 at end. Your loop is correct and works just fine :). That's return value of the i++ expression, which you are mistaking for console.log in developer console. Try this, you will figure it out;
var i=0;do{console.log('i = ', i);i++;}while(i<5);
Edit Thanks to #ggorlen for pointing this out, it's the return value of last expression in block({}) which is i++, i increments the value and returns it's last value (if i = 4; i++ returns 4 and makes value of i = 5), (++i, returns 5 and makes value of i = 5)
var i=0;do{console.log('i = ', i);++i;}while(i<5);
will give return value of 5
JavaScript has the concept of "Completion Records". Basically every statement produces a completion record.
The Completion type is a Record used to explain the runtime propagation of values and control flow such as the behaviour of statements (break, continue, return and throw) that perform nonlocal transfers of control.
You usually cannot do anything with these in user land code, but the runtime needs those to properly execute your program. However the Chrome console will print the value of the completion record of the last statement it executes.
Without going into to much details, here is what happens:
The value of the completion record of the do...while loop is the value of the completion record of its body.
The body is a block with a statement list. The value of the completion value of a statement list is the value of the completion record of the last statement in the list.
The last statement is an expression statement (i++;). The value of the completion record of an expression is the value the expression evaluates to.
The simplest example to demonstrate this behavior is simply
42;
The result of evaluating this expression statement is a completion record that looks something like
{
type: normal,
value: 42,
target: empty
}
You will see it print 42 in the console because that's the value of the completion record of the expression statement.
A slightly more evolved example:
if (true) {
42;
}
will print the same.
Yeah, it's normal that extra 4.
It's called expression evaluation. Id doesn't mean it's printing, but instead evaluating i to you.
Check here to know more about it.
This is just chrome helping you to know the dynamic environment of your variables.

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);

What is the difference in between those pieces of code? [duplicate]

This question already has answers here:
Javascript function in setInterval
(3 answers)
Closed 8 years ago.
What is the difference in between:
k = setInterval(function(){loop();},100);
and
k = setInterval(loop(),100);
Why does the second one run once, like the setTimeout() function and the first one every 1/10 of a second?
In second one you are actually executing loop before setInterval is called, so you are passing result of the loop to the setInterval
More similar would be
k = setInterval(function(){loop();},100);
k = setInterval(loop,100);
first example allows you to do some work before calling loop and to pass some arguments if necessary
second one requires a function object as a 1st parameter and you cannot pass anything inside the brackets.
1st one is more widely spread pattern than 2nd (which is a little bit obsolete)
Lets checkout how doest JS run this code:
Fist way -
JS see setInterval - it should have 2 arguments and timer - in first variant everythink is trivial - you passed a function to be called on each interval and timer.
Lets check second variant - again setInterval, 2 params . But this time you dont pass link to function but called function and the result of this function will be passed to the setInterval. As you called function - it runs once, as it doesent return function setInterval cant run anything.

Categories