2

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?

3 Answers3

2

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.

FeifanZ
  • 16,250
  • 7
  • 45
  • 84
  • Thanks, but would it fall under the category of conventional loops? (I dont have anything against loops just so you know) – learning2code Jan 18 '15 at 01:17
  • 1
    Yes — the definition of loop in a programming context is a way to do something multiple times. You can layer syntax and structures on top to hide the loop, but (at least within the realm of 'recognizable' programs) it's still a loop. – FeifanZ Jan 18 '15 at 01:18
2

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);
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

Using Underscore.js (website) (GitHub), you can use times():

function sayHi() {
    alert('hi');
}

_.times(3, sayHi);
joshreesjones
  • 1,934
  • 5
  • 24
  • 42