0

I'm making a Chronometer and i don't understand why when i use a function with parameters it doesn't work but when I write the entire function code replacing the values, it works perfectly, I'm using TypeScript by the way

function countHundrethsOrSeconds(
  countedTime: number,
  timeChange: number,
  timeGrouping: number,
  timeShower: string,
) {
  countedTime += timeChange;
  if (countedTime === timeGrouping) {
    countedTime = 0;
  };
  if (countedTime.toString().length === 1) {
    chronoAndTimer[timeShower as keyof typeof chronoAndTimer].textContent = '0' + countedTime.toString();
  }
  else {
    chronoAndTimer[timeShower as keyof typeof chronoAndTimer].textContent = countedTime.toString();
  };
};

//some code

secondsInterval = setInterval((): void => {
    countHundrethsOrSeconds(seconds, 1, 60, 'secondsShower');
    }, 1000);
//doesn't work

secondsInterval = setInterval((): void => {
    seconds += 1;
  if (seconds === 60) {
    seconds = 0;
  };
  if (seconds.toString().length === 1) {
    chronoAndTimer['secondsShower'].textContent = '0' + countedTime.toString();
  }
  else {
    chronoAndTimer['secondsShower'].textContent = countedTime.toString();
    }, 1000);
//works but I'm capricious and I want to save lines

The interval doesn't work, I also used a timeOut and it works so I don't know what am I missing.

starball
  • 20,030
  • 7
  • 43
  • 238
  • Calling `countHundrethsOrSeconds(seconds, ....)` and then inside the function doing `countedTime += timeChange` is not equivalent to `seconds += 1`. In the first approach, `seconds` is never changed. – Titus Jul 06 '23 at 04:41
  • Ok, thank you, I'm just going to do the increment/decrement outside de function. – Carmelo Jul 06 '23 at 04:53
  • You can do it inside, but if seconds is a global variable you shouldn't pass its value as a parameter but directly changes its value inside the function – Florent M. Jul 06 '23 at 07:36

0 Answers0