Asynchronous (setTimeout) lambda doesn't use correct inputs [duplicate] - javascript

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Javascript setTimeout, Loops and Closure
(1 answer)
Closed 9 years ago.
I got the below code within a callback of xmlHTTPRequest callback function:
// some more code before
...
// schedule the UI update
var totSteps = 6;
for(var i = 0; i < listChangeEl.length; ++i) {
// callback pulse function
var curPulse = function cell_pulse(elName, curCnt) {
console.log("Accessing element: " + elName);
var curEl = document.getElementById(elName);
console.log("Element: " + elName + " = " + curEl);
var curColor = RGB2HTML(255, 255*(curCnt/totSteps), 255*(curCnt/totSteps));
if(curCnt < totSteps) {
// recursion here!
setTimeout( function(){ cell_pulse(elName, curCnt+1); }, 125);
}
};
// start it!
setTimeout( function() { (curPulse)(listChangeEl[i], 0); }, 125);
}
Apparently when the above is setTimeout( function() { (curPulse)(listChangeEl[i], 0); }, 125); is executed , listChangeEl[i] does contain the right id of a cell I want to update, but then, upon first execution of function cell_pulse the parameter elName is undefined.
What am I doing wrong? Does Javascript manage lambda (of lamdba) properly?
Thanks,
Ema

Related

Problem fetching value in Array - XMLHttpRequest [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 years ago.
I am trying to make multiple requests on the server within a loop for. I found some tips here and implemented the suggested solution. However, it does not seem to work.
var valuePlan = [];
function getValue(id) {
var f = (function(){
var xhr = [], i;
for(i = 0; i < id.length; i++){ //for loop
(function(i){
xhr[i] = new XMLHttpRequest();
url = "get.php?id=" + id[i] + "&for=monthly";
xhr[i].open("GET", url, true);
xhr[i].onreadystatechange = function(){
if (xhr[i].readyState === 4 && xhr[i].status === 200){
console.log('Response from request ' + i + ' [ ' + xhr[i].responseText + ']');
valuePlan.push(xhr[i].responseText.replace(".", ","));
}
};
xhr[i].send();
})(i);
}
})();
};
getValue([48,52,50]);
console.log(valuePlan[0]);
The problem that when I use console.log(valuePlan[0]); in console it returns undefined, and if it uses console.log(valuePlan); returns the arrays with the correct values. Can you understand that?
The variable is already defined as global, and even then I can not fetch the individual values of it.

Order of execution with setTimeout JS [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm trying to define a global variable value, from a function which is executed with the timeout method. The problem I'm facing here is can't get rid of the time interval.
*** Not Working (But I want the goal variable to be outside so that I can access it later).
function demo() {
var noOfGoals = 4;
goal = "He has scored " + noOfGoals + " in 45 Mins";
}
setTimeout(function() {
demo();
}, 2000);
console.log(goal);
****Working(but I dont want to access it from setTimeout)
function demo() {
var noOfGoals = 4;
goal = "He has scored " + noOfGoals + " in 45 Mins";
}
setTimeout(function() {
demo();
console.log(goal);
}, 2000);
Any new ideas or a better apporach than how have I done!
You can't get a return value from the function you pass to setTimeout.
For what you want to do, that would be written as:
function demo() {
var noOfGoals = 4;
return goal = "He has scored " + noOfGoals + " in 45 Mins";
}
function launch_goal () {
setTimeout(function() {
console.log(demo());
}, 2000);
}
launch_goal();
Or the other way to do it, you will need to use Promises

JavaScript: Why isn't this callback function not working? [duplicate]

This question already has an answer here:
Maximum call stack size exceeded on SetTimeout recursive function (Javascript) [duplicate]
(1 answer)
Closed 5 years ago.
It says: TypeError: myFunc is not a function
I want the output to be "I am happy, haha!".
I'm learning callback functions in JS.
function emotions(myString, myFunc) {
console.log("I am " + myString + ", " + myFunc(2));
}
var laugh = function(val) {
var ha="";
for(var i=0;i<val; i++) {
ha=ha+"ha";
}
return ha;
};
emotions("happy",laugh(2));
Try this:
emotions("happy", laugh);
You're having that issue because you're no passing the function itself, but it's result as the parameter. When you do laugh() you are running the function, not using it's reference, hence, you're passing it's result instead.
The call will the executed inside the emotions function as laugh(2), so that's the correct way.
function emotions(myString, myFunc) {
console.log("I am " + myString + ", " + myFunc(2));
}
var laugh = function(val) {
var ha="";
for(var i=0;i<val; i++) {
ha=ha+"ha";
}
return ha;
};
console.log(emotions("happy",laugh));

How to correctly reference an object method within itself in Javascript? [duplicate]

This question already has answers here:
Referencing "this" inside setInterval/setTimeout within object prototype methods [duplicate]
(2 answers)
Closed 8 years ago.
What is the correct way to reference an object function from within itself, so that I can call it several times using setTimeout in Javascript? In other words I want to be able to do this:
Foo.prototype.move = function() {
if (this.count_a < 5) {
this.count_a += 1;
// setTimeout(this.move, 500); // doesn't work
// setTimeout(function() { this.move(); }, 500); // doesn't work
}
}
I have tried a couple of things, none of which seem to work: http://jsfiddle.net/tga8r/1/
this has a global scope when the window timer function runs- it is out of your function and in the window.
label the this-
Foo.prototype.move= function(){
var T= this;
if(T.count_a<5){
T.count_a += 1;
setTimeout(function(){T.move();},500);
}
}
The this property within the timeout will point to the object, that does execute the passed callback.
use .bind(this) to say, that the invoker have to use the this point to the passed object.
Foo.prototype.move = function() {
if (this.count_a < 5) {
this.count_a += 1;
// setTimeout(this.move, 500);
setTimeout(function() { this.move(); }.bind(this), 500);
}
}
or use a reference:
Foo.prototype.move = function() {
var self = this;
if (this.count_a < 5) {
this.count_a += 1;
// setTimeout(this.move, 500);
setTimeout(function() { self.move(); }, 500);
}
}
function move (a) {
setTimeout(
function() {
if (a < 10) {
a = a+ 1;
move(a);
}
}, 500); }
move(0);

how to get exact value in setTimeout function [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
javascript using settimeout() with a loop
(4 answers)
Closed 9 years ago.
Simple question...
for (var i = 0; i < 5; i++) {
setTimeout(function () { alert(i) }, 3000);
}
how to alert 5 times with exact value of i.
It gives "5" only 5 times.
I need its result like
0
1
2
3
4
With a closure that keeps the value of the variable constant within the new scope of the immediately invoked function
for (var i = 0; i < 5; i++) {
(function(j) {
setTimeout(function () { alert(j) }, 3000);
}(i));
}
The setTimout is asynchronous, so by the time it executes the loop has long since completed, and the value of i has been changed to 5, so you need to lock it in.
You can use setInterval alternate to setTimeout
Try,
var xCnt = 0;
var xInterval = setInterval(function()
{
xCnt +=1;
alert(xCnt);
if(xCnt == 5)
{
clearInterval(xInterval);
}
}, 3000);
DEMO

Categories

Resources