Is there a function that I can use to execute commands multiple times...
alert('hi');
alert('hi');
alert('hi');
so that I can do this without repitition.
Is there a way to do this with a preset function to eliminate redundancy?
Is there a function that I can use to execute commands multiple times...
alert('hi');
alert('hi');
alert('hi');
so that I can do this without repitition.
Is there a way to do this with a preset function to eliminate redundancy?
The 'preset functionality' would simply be a loop, in one form or another. You could use Coffeescript's comprehensions:
alert('hi') for num in [1..10]
http://coffeescript.org/#loops
But that's still a loop :)
Some languages, like Ruby, have a construct like
10.times do { puts 'hi' }
Unfortunately, the same isn't available in JS.
There is not something built into the Javascript language that lets you repeat a function multiple times, but you can easily create a function to do that for you:
function execMultiple(fn, num, /* args */) {
// make copy of the args without the first two items
var args = Array.prototype.slice.call(arguments, 2);
for (var i = 0; i < num; i++) {
fn.apply(this, args);
}
}
execMultiple(alert, 3, 'hi');
Or, you could require a stub function with args already in it be passed in:
function execN(fn, n) {
for (var i = 0; i < n; i++) {
fn();
}
}
execN(function() {
alert('hi');
}, 3);
Using Underscore.js (website) (GitHub), you can use times():
function sayHi() {
alert('hi');
}
_.times(3, sayHi);