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

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.

Related

How to pass variables when using JS setTimeout() [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 1 year ago.
I am using clippy.js to make the characters in the viewport speak through a ballon. I would like to have the characters speak texts in a sequence by passing elements in an array that contains the different texts with a delay in between speaking the texts. For this I am using a for loop with a specific delay the between passings of the text. That part works well using setTimeout(), but, likely because of the asynchronous nature of JS, only the last text variable is passed to the function. Here is the code snippet:
for (n=0;n<4;++n){
x = tmptext[n];
setTimeout(() => {agent.speak(x);}, 5000 + n*5000);
}
tmptext[] is an array that contains the different texts, and cagent.speak() is the function for making the character speak a text, which otherwise works well. The problem is that the character only speaks the last text in the array 4 times although it does so with the proper timing between them. Clearly, the function is executed 4 times using only the value of the variable x as assigned to it in the last iteration in the for loop (which is the value of x=tmptext[3] in this case).
If I use the tmptext[] array directly, I get no text at all passed from this array into the function. For instance,
for (n=0;n<4;++n){
setTimeout(() => {agent.speak(tmptext[n]);}, 5000 + n*5000);
}
Here, no text is passed as confirmed by using alert in the cagent.speak() function to monitor this, and indeed the balloon appears empty 4 times. This is because the value of n that is being used is of its last value in for iteration which makes it 5 and beyond the scope of the array.
The asynchronous nature of JS seems to be the problem here and I am not familiar in dealing with it. How do I pass the value of each element in the array into the function with the proper timing in between? Would appreciate help here.
This code solved the problem:
for (n=0;n<4;++n){
let x = tmptext[n];
setTimeout(() => {agent.speak(x);}, 5000 + n*5000);
}

Functions that call eachother [duplicate]

This question already has answers here:
Are variables statically or dynamically "scoped" in javascript?
(7 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 2 years ago.
I am looking for someone to explain me something since I can't find a clear answer. My question is about functions that call themselves. I saw that it is possible to build a list of functions that are 'chained' together and for example the first function calls the second one then the second one calls another one. My confusion is : Lets say that you have a second function that has a variable let a = 12; if i call that function on the first function, will i have access to that variable or whatever that second function might have inside? How can i pass info to another function? can a function can be dependent on another function in order to complete a task? Thanks in advance guys.
Edit to make it more clear what I mean:
function first(){
second();
// will i have access to whatever there is inside function second since i am calling it here ? or it doesn't work that way?
}
function second(){
let a = 12;
third();
}
function third(){
fourth()....
}

How can I make a part of code wait without halting everything else in JavaScript? [duplicate]

This question already has answers here:
setTimeout ignores timeout? (Fires immediately) [duplicate]
(3 answers)
Closed 3 years ago.
So, I need to make a function wait a time interval before executing, however, I need the rest of the code to execute while this wait is happening. Basically, I want to change variables in function of time passed without having to make all code wait for that to be executed.
I'll give an example so you can understand me better.
function example(){
sampleCode();
}
var x = 0;
if(x > 0){
console.log("enough time has passed")
}
example();
Take in mind that the whole block of code is being repeated multiple times a second, it's not a single execution program. I need to make x greater than 0 without preventing "example" from executing, so, setInterval is a nono (unless it has a functionality I'm not aware of). How can I do this? (Ignore the fact that x is being defined in this scope, so it's being set to 0 over and over, pretend it's a global variable).
EDIT: I've been recommended to use setTimeout and to show how I use it, here's how:
function handleMouseClick(evt){
[...]
setTimeout(test(), 3000);
}
function test(){
alert("Testing");
}
This results in an instant display of alert, no matter how much time i put into the timeout. What's wrong?
The issue you have is that you are not properly using the setTimeout function. You need to remove the parentheses from your call.
setTimeout(test, 3000);
Downvoters; I will make a more thorough and detailed answer for future readers later today when I’m at a computer. I am currently on break and do not have my computer with me. You can view some of my other answers to set your mind at ease that I will be back to flesh out a more detailed answer.

Behaviour of setTimeout Inside console.log [duplicate]

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.

what's the statement execution order of this JS closure ? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I have known the key of closure is about scope. But I don't know the specific execution order of it.
A classical code from 《Professional JavaScript for Web Developers 3rd Edition》about closures.
function createFunctions(){
var result=new Array();
alert('haha');
for(var i=0;i<10;i++){
result[i]=function(){
alert(i);
return i;
};
}
return result;
}
var a=createFunctions();
To my surprise, 'haha' was alerted while none of 'i' were alerted.I was just assigning the function to variable a.Why the statement "alert('haha')" was alerted while the cycle wasn' t executed?
when I add the below code,
var a=createFunctions();
alert(a[2]);
why it alerted like this
function (){
return i;
}
not like
function (){
return 2;
}
Furthermore when I add the below code, what will being the order of statements executed especially the statements in the cycle.
var a=createFunctions();
alert(a[2]());
When you call
var a=createFunctions()
alert('haha') is executed immediately, and an array of 10 functions is created and assigned to the variable 'a', each function alerting 'i' and returning it.
However, by the time any of those functions is called (provided you call them after creating them) the value of i is '10' (the loop termination value). So every time you call one of the functions, with
alert(a[x]())
( with any value of x = 0 thru 9 )
it will alert(10) as the function executes and alert(10) again when it returns.
Why the statement "alert('haha')" was alerted
Because it was an alert statement in the function you called.
while the cycle wasn' t executed
The cycle was executed. The cycle just creates some functions and assigns them to positions in an array. You never call any of those functions.
and when I add the below code, what will being the order of statements executed
It depends where you add it.

Categories