'Counter in Node.js

I'm trying to make a Node.js counter function which will count in the terminal until I stop it. However, I'm having a problem with it.

Here's my code:

async function test() {
  var count = 1
  var newcount = count + 1
  var count = newcount
  console.log(count)
}

The count stays on 1. I know why this is, I just don't know how to fix it. It stays on 1 because I'm declaring it as 1 every loop. It does go to 2, but it doesn't go any higher because of what I just said. I can't figure out how to stop it from declaring as 1 every loop.

So if anyone could help, that'd be great.

Edit:

I forgot to put this in my code snippet:

setInterval(test, 10000)


Solution 1:[1]

First of all why are you using async while you don't need it / use await?

The reason why your function is not working is that you are not looping over your variable. Your function should look something like this.

function counter() {
  let count = 0
  setInterval(() => {
    count++;
    console.log(count)
  }, 1000)
}

Solution 2:[2]

Every time you run the function test() it will reset the counter to 1

  var count = 1

You should declare the variable outside of the function (global variable) or use a function parameter and returning the new value. Examples would be

// Using a global variable
var count = 1;
function countFunction() {
  var newcount = count + 1;
  count = newcount;
  console.log(count);
}

// To use this inside a setInterval
setInterval(countFunction, 10000);

// Using a function parameter and returning value
var count = 1
function countFunction(countParameter=0) {
  return countParameter+1;
}

count = countFunction(count); // 2
count = countFunction(count); // 3
count = countFunction(count); // 4
count = countFunction(count); // 5

// To use this inside a setInterval
var count=1
setInterval(()=>{count = countFunction(count)}, 10000)

enter image description here enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex
Solution 2