Hi I'm trying to add some events to my page with a loop. this is my code
elements = $(".my-elements")
var i;
for (i = 0; i < elements.length; i++) {
e = elements[i];
document.addEventListener('scroll', event => {
if( inViewport(e) ) {
$(e).css({opacity: 1.0})
}
})
}
But after running the code, only the last event is applied, and previous events have no effect.
what's the problem?
Try this:
elements = $(".my-elements")
var i;
for (i = 0; i < elements.length; i++) {
function() {
var e = elements[i];
document.addEventListener('scroll', event => {
if( inViewport(e) ) {
$(e).css({opacity: 1.0})
}
})
}()
}
i think the method is running synchronously,
try to put it into an [async method][1], await for the function inside it and return a promise in each iteration.
it will stop the execution of the async function until one iteration is completed
like-
async function myEvent(){
elements = $(".my-elements")
var i;
for (i = 0; i < elements.length; i++) {
await function() {
return new Promise((resolve,reject)=>{
var e = elements[i];
document.addEventListener('scroll', event => {
if( inViewport(e) ) {
$(e).css({opacity: 1.0})
resolve();
}else{
resolve();
}
})
})
}
}
}
if there's an error in snippet you can correct it but take my point of going async.
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Related
I have the following script that opens urls in a list:
function openWindow(){
var x = document.getElementById('a').value.split('\n');
for (var i = 0; i < x.length; i++)
if (x[i].indexOf('.') > 0)
if (x[i].indexOf('://') < 0)
window.open('http://'+x[i]);
else
window.open(x[i]);
}
However, I would like to add a delay (let's say about 5 seconds) between opening each url. How can I do this?
I'm not familiar with functions. Usually much better with Linux and such. Your insight is highly appreciated.
A better approach is to use setTimeout() along with a self-executing anonymous function:
function openWindow() {
var i = 0;
var x = document.getElementById('a').value.split('\n');
(function() {
if(typeof x[i] !== 'undefined') {
if(x[i].indexOf('.') > 0) {
if(x[i].indexOf('://') < 0) {
window.open('http://' + x[i++]);
} else {
window.open(x[i++]);
}
}
setTimeout(arguments.callee, 1000);
}
return false;
})();
}
This will guarantee that the next call is not made before your code was executed. I used arguments.callee in this example as a function reference. Once the index no longer exists in the array, by checking if it's undefined, it simply returns false instead of setting another timout.
You can do it like this, to avoid issues caused by setTimeout being non-blocking.
What you need is to wait for the setTimeout to be executed before starting the next iteration.
var i = 0;
function openWindow(){
var x = document.getElementById('a').value.split('\n');
doLoop(x);
}
function doLoop(x)
setTimeout(function () {
if (x[i].indexOf('.') > 0){
if (x[i].indexOf('://') < 0){
window.open('http://'+x[i]);
}else{
window.open(x[i]);
}
}
i+=1;
if(i<x.length){
doLoop(x);
}
}, 5000)
}
Using a self executing function, it'd go like this :
function openWindow() {
var i = 0;
var x = document.getElementById('a').value.split('\n');
(function fn() {
if(x[i].indexOf('.') > 0) {
if(x[i].indexOf('://') < 0) {
window.open('http://' + x[i++]);
} else {
window.open(x[i++]);
}
}
i++;
if( i < x.length ){
setTimeout( fn, 3000 );
}
})();
}
create array x with all url's
var x = [url1, url2, url3, ...];
create a for loop
for(var i = 0; i<x.length; i++) {
setTimeout(function() {
window.open('http://'+x[i])}, 1000); // 1000 for 1 second
}
}
setInterval(function(){window.open('http://'+x[i]);},5000);
I'm creating an object literal and I want to use the reserved word "this". The problem I'm having is that the "this" points to the window object in an object literal. I know the this points to the current object when used in a constructor function. Is there a way to override it so that "this" points to my object literal?
main = {
run: function()
{
var elements = [];
var allElements = document.querySelectorAll("*");
for(var i = 0; i < allElements.length; i++)
{
if(allElements[i].nodeType != 3)
{
elements.push(allElements[i]);
}
}
for(var i = 0; i < elements.length; i++)
{
// Doesn't work
// this.parseElement(elements[i]);
// Works
main.parseElement(elements[i]);
}
},
parseElement: function(e)
{
// Unimportant code
}
}
(function()
{
main.run();
})();
The thing you claim works in your question doesn't work:
var main = {
run: (function()
{
var elements = [];
var allElements = document.querySelectorAll("*");
for(var i = 0; i < allElements.length; i++)
{
if(allElements[i].nodeType != 3)
{
elements.push(allElements[i]);
}
}
for(var i = 0; i < elements.length; i++)
{
// Doesn't work
// this.parseElement(elements[i]);
// Works
main.parseElement(elements[i]);
}
})(),
parseElement: function(e)
{
// Unimportant code
}
};
<div></div>
Fundamentally, you cannot refer to the object being constructed from within the object initializer. You have to create the object first, because during the processing of the initializer, while the object does exist no reference to it is available to your code yet.
From the name run, it seems like you want run to be a method, which it isn't in your code (you've edited the question now to make it one). Just remove the ()() around the function:
var main = {
run: function() {
var elements = [];
var allElements = document.querySelectorAll("*");
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].nodeType != 3) {
elements.push(allElements[i]);
}
}
for (var i = 0; i < elements.length; i++) {
this.parseElement(elements[i]);
}
},
parseElement: function(e) {
console.log("Parsing " + e.tagName);
}
};
main.run();
<div></div>
Since this is set by how the function is called for normal functions, if you want run to be bound to main so that it doesn't matter how it's called, using main instead of this is the simplest way to do that in that code.
But if you don't want to use main, you could create a bound function:
var main = {
run: function() {
var elements = [];
var allElements = document.querySelectorAll("*");
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].nodeType != 3) {
elements.push(allElements[i]);
}
}
for (var i = 0; i < elements.length; i++) {
this.parseElement(elements[i]);
}
},
parseElement: function(e) {
console.log("Parsing " + e.tagName);
}
};
// Bind run
main.run = main.run.bind(main);
// Use it such that `this` would have been wrong
// if we hadn't bound it:
var f = main.run;
f();
<div></div>
Just as a side note, we can use Array.prototype.filter and Array.prototype.forEach to make that code a bit more concise:
var main = {
run: function() {
var allElements = document.querySelectorAll("*");
var elements = Array.prototype.filter.call(allElements, function(e) {
return e.nodeType != 3;
});
elements.forEach(this.parseElement, this);
},
parseElement: function(e) {
console.log("Parsing " + e.tagName);
}
};
// Use it
main.run();
<div></div>
That assumes that parseElement only ever looks at the first argument it's given (since forEach will call it with three: the entry we're visiting, its index, and the object we're looping through).
in my React-native app I am trying to call another function within my listenForItems function, but keep getting the error this.populateArray is not a function. In 'this.populateArray(solutions)', this.populateArray is undefined. I do this in other classes and it's working, but for some reason it's not working here. Is there anything I'm missing?
populateArray: function(solutions) {
var completed = [];
var inProgress;
for (var i = 0; i < solutions.length; i++ ) {
if (solutions[i].completed == 0) {
inProgress = solutions[i].id;
}
else {
completed.push(solutions[i].id);
}
}
},
listenForItems: function(cluesRef) {
var solutions = [];
userSolutionsRef.orderByChild('user_id').startAt(0).endAt(0).once('value', function(snap){
var solution = snap.val();
for (var i = 0; i < solution.length; i++) {
if (solution[0].hunt_id == 0) {
solutions.push(solution[0]);
}
}
this.populateArray(solutions);
});
},
The classic this scope issue of javascript. Google will help with better understanding. In short, the word "this" inside a function refers to that function. In this example it refers the anonymous function (callback) that you use in userSolutionsRef.orderByChild. There are many ways to solve this. You can use ES6(ES2015) arrow functions in which case it becomes something like
userSolutionsRef.orderByChild('user_id').startAt(0).endAt(0).once('value', (snap) => {
var solution = snap.val();
for (var i = 0; i < solution.length; i++) {
if (solution[0].hunt_id == 0) {
solutions.push(solution[0]);
}
}
this.populateArray(solutions);
});
or es5 solution
var that = this;
userSolutionsRef.orderByChild('user_id').startAt(0).endAt(0).once('value', function(snap){
var solution = snap.val();
for (var i = 0; i < solution.length; i++) {
if (solution[0].hunt_id == 0) {
solutions.push(solution[0]);
}
}
that.populateArray(solutions);
});
for (var e = 0; e < markers.length; e += 1) {
(function (e, markers, latLngBounds) {
if (latLngBounds.contains(markers[e])) {
updatePrompt("Marker is contained");
// Break for loop
}
})();
}
In the example above, after the updatePrompt method is invoked how can I break out of the loop containing the closure?
var broken = false;
for (var e = 0; e < markers.length; e += 1) {
if (broken) {
break;
} else {
(function (e, markers, latLngBounds) {
if (latLngBounds.contains(markers[e])) {
updatePrompt("Marker is contained");
broken = true;
}
})();
}
}
A little verbose, but you get the point.
This could also be done with Array.some in modern browsers
markers.some(function(marker) {
if (latLngBounds.contains(marker)) {
updatePrompt("Marker is contained");
return true;
}
return false;
});
not sure if i get you correct, but if you want to break the loop set
e= markers.length;
The loop will not continue after this statement
Another way:
for (var e = 0; e < markers.length; e += 1) {
if ((function (e, markers, latLngBounds) {
if (latLngBounds.contains(markers[e])) {
updatePrompt("Marker is contained");
return 1;
}
return 0;
})())
break;
}
Hello I am using function
function prepareRadios(radioGroupName) {
var radios = document.getElementsByName(radioGroupName);
for( i = 0; i < radios.length; i++ ) {
document.getElementById(radios[i].id).onchange = function() {
radioUpdated(radioGroupName, radios[i].id);
};
}
}
the problem is, that the onchange event fires with quote (radioGroupName, radios[i].id) instead of having those values put into it with my function
I need to pass the VALUES of them, not the names of the vars
What am I doing wrong?
It's closure-time :)
function prepareRadios(radioGroupName) {
var radios = document.getElementsByName(radioGroupName);
for( i = 0; i < radios.length; i++ ) {
document.getElementById(radios[i].id).onchange = (function(name, id) {
return function() { radioUpdated(name, id); }
})(radioGroupName, radios[i].id);
}
}