Cody
Cody

Reputation: 929

How to repeat execution in nodejs

Basically, I want to repeat the console.log for 5 times I use repeating - npm This might sound very basic but I can't figure out how to use this to simply repeat the console.log('test'); for 5 times using nodejs I need this for a node application that should repeat a special code multiple times in nodejs. Hope someone here might know a solution to it.

app.js

const repeating = require("repeating");

repeating(5, console.log('test'));

Upvotes: 3

Views: 4736

Answers (1)

Fatih Aktaş
Fatih Aktaş

Reputation: 1574

You use repeating to print repeating strings:

const repeating = require('repeating');

console.log(repeating(100, 'unicorn '));

Check DOCS. repeating(count, [string]) function only takes a string.


For calling a function multiple times, you could use a for loop.

for (var i = 0; i < 5; i++) {
  console.log("Hi");
}

The code above would be like below in one line for loop

for (var i = 0; i < 5; i++) console.log("Hi");

You can have recursion.

(function repeat(number) {
  console.log("Hi");
  if (number > 1) repeat(number - 1);
})(5);

There are more examples in this comment.

Upvotes: 2

Related Questions