This isn't totally necessary, I'm just trying to simplify my code. This is what I have:
function fillWebsitePlaceFiller(number) {
document.getElementById("placefillerWebsite" + number).innerHTML = placefillerWebsite;
}
fillWebsitePlaceFiller(1);
fillWebsitePlaceFiller(2);
fillWebsitePlaceFiller(3);
fillWebsitePlaceFiller(4);
fillWebsitePlaceFiller(5);
fillWebsitePlaceFiller(6);
fillWebsitePlaceFiller(7);
Is there a way I can call the function just once, and it will run through it 7 times with each argument?
In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.
Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.
The setInterval() method repeats a given function at every given time-interval.
This type of function / operation is called Idempotent.
Method 1 - iteration
for (var i = 1; i < 8; i++) fillWebsitePlaceFilter(i);
Method 2 - recursion
(function repeat(number) {
fillWebsitePlaceFiller(number);
if (number > 1) repeat(number - 1);
})(7);
Method 3 - functor application
[1, 2, 3, 4, 5, 6, 7].forEach(fillWebsitePlaceFiller);
Method 4 - internal iteration
function fillWebsitePlaceFiller(times) {
for (var number = 1; number <= times; number++) {
document.getElementById("placefillerWebsite" + number).innerHTML = placefillerWebsite;
}
}
Method 5 - extend function behaviour
Function.prototype.sequence = function(from, to) {
for (var i = from; i <= to; i++) this.call(null, i);
};
fillWebsitePlaceFiller.sequence(1, 7);
Method 6 - XPath (warning: not tested)
var query = '//*[@id[starts-with(., "placefillerWebsite"]]';
var result = document.evaluate(query, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
while (var node = result.iterateNext()) node.innerHTML = placefillerWebsite;
Method 7 - jQuery
$('[id^="placefillerWebsite"]').html(placefillerWebsite)
I recommend one of the methods where you don't assume there are always seven of them.
With ES6 it can be solved a bit more elegantly:
[...Array(7)].forEach((_, i) => fillWebsitePlaceFiller(i + 1))
A simple for loop!
for (var i = 1; i <= 7; ++i) {
fillWebsitePlaceFiller(i);
}
Or, just as easily, modify fillWebsitePlaceFiller to do its own for loop:
function fillWebsitePlaceFiller() {
for (var i = 1; i <= 7; ++i) {
document.getElementById("placefillerWebsite" + i).innerHTML = placefillerWebsite;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With