jQuery images preload callback in loop [duplicate] - javascript

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I am writing script for lightbox gallery. I want to user prelaod techique for elegant image loading. My current script is:
for (var i in imgs) {
var tmp_thumb=$('img');
tmp_thumb.on('load', function(){
O.SG.thumbs.append('<li><a style="background-image:url(\'' + imgs[i].thumb + '\')"></a></li>');
$(this.)remove();
}).attr('src', imgs[i].thumb);
}
The problem is, when load callback is called, loop counter i has almost always the last value from img array.
How to pass to callback the proper value of i from the context of lode

The problem is nothing stops your loop, you are setting a bunch of callbacks and by the time they begin getting called, the value of i has hit the end. Try using deferreds. There are examples online. Here's a pretty decent one: http://aboutcode.net/2013/01/09/load-images-with-jquery-deferred.html

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

Javascript code doesn't execute after the page changes [duplicate]

This question already has answers here:
Is there a way to have an onload callback after changing window.location.href?
(3 answers)
Closed 4 years ago.
So, I'm trying to run this code
document.location = "https://stackoverflow.com/questions/ask";
document.onload = function(){document.getElementById("title").value="My question";};
but it turns out that my function doesn't run the function. You can observe this by doing
document.location = "https://stackoverflow.com/questions/ask";
document.onload = function(){document.getElementById("title").value="My question";alert('Hi');};
My question is, what am I doing wrong? Why doesn't the function run?
Something similar was asked here!
Here is a quote of the most important part of the accepted and most upvoted answer:
No, you cannot do it the way you want. Loading a new page closes the current document and starts loading a new document. Any code in your current document will no longer be active when the new page starts to load. - Source: Answer by jfriend00

EventListener calling a function() prematurely [duplicate]

This question already has answers here:
Javascript "addEventListener" Event Fires on Page Load [duplicate]
(2 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
My EventListener is calling the function before the click with this code... what's wrong with that line?
It was working fine when I had the function inside the parameter, but now that i'm calling it from there instead it's calling it prematurely before any click occurs.
divs[i].addEventListener('click', xopush(i), null);
It's calling a function with and argument passing to the function()... not an alert.
//Instead of EventListener I usually prefer to use...
divs[i].onclick = function() {
xopush(i);
}
... which is a answer to this. However, I was looking forward to using the eventListener so I could turn it off after 1 click on the element.

Why shouldn't I make functions within a loop in Javascript? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
In JavaScript, what are specific reasons why creating functions within a loop can be computationally wasteful?
(2 answers)
Closed 8 years ago.
I checked over my script the other day with JSFiddle and got a warning on one of the lines: Don't make functions within a loop.
for (x = 0; x < 10; x++) {
if (moment(now) > moment(then)) {
doIt(x); // do it now
} else {
timeTillEnd = moment(then) - moment(now);
setTimeout(function () {
doIt(x); // do it later
}, timeTillEnd); // <-- flagged here
}
}
Why shouldn't I make functions within a loop in Javascript?
Also: Could the usage of a function in the particular situation shown here be problematic?
What you are trying to do is probably wrong, the x variable might not be what you expect it to be. See the following link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake
And they are also relatively expensive to create.
Each function comes with the closure of the variables it uses, that is an unnecessary overhead if you are doing "normal imperative programming" and just want to make the code look clearer by defining inner functions for sub-tasks:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Performance_considerations
In your case, it seems that you actually need a function with its closure, since you are deferring some computation, but make sure that you do the proper value capture.
Because it can lead to unexpected closure behaviour (the captured variable will have the value assigned in the last iteration of the loop). You will also get a new instance of the function for each loop which is wasteful of resources.
Modern browsers take a third argument for setTimeout which is the argument to the function. See here. This also gets rid of the problems with closures.

dynamically adding javascript eventlistener doing unexplainable things [duplicate]

This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 9 years ago.
Currently working on a piece of code that is supposed to add eventlisteners to images on a page in a dynamical way.
var images = document.getElementsByClassName("imageBox");
function imageZoomer(imageName) {
console.log(imageName);
}
for(var i = 0; i < images.length; i++) {
images[i].addEventListener("click", function(){imageZoomer(i)}, false);
}
However the i is showing different values then I expect. At first everything is going wel. It iterates just like it's suppose to do. But on my test page with 2 images the console log reveals '2' at both the images.
This happens because i keeps incrementing and by the time you click an image i is probably images.length - 1. You need a way to save the current i in each handler. You can store that value on each image (images[i].index = i; usually works) and retrieve it later but finding the object is a pain - it'd end up being something like:
images[i].index = i;
images[i].addEventListener("click", function(e){imageZoomer(e.target.index)}, false);
However, I've found the slickest way to do this is using an IIFE (read: iffy - Immediately Invoked Function Expression) to restrict the scope of i to whatever it was when the event was created. That looks something like:
images[i].addEventListener("click", (function(i){return function(){imageZoomer(i)}})(i))
IIFEs are super powerful. Take a look at Ben Alman's post: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Categories