#TS and setInterval/clearInterval

1 messages · Page 1 of 1 (latest)

chrome wave
#

Newbie here trying to learn TS and JS with practice.
I don't know how to resolve the issue of the setTimer variable/function from being underlined.

The error message is: Argument of type '(buttonPress: string) => void' is not assignable to parameter of type 'number'.

const startButton = document.querySelector('#start') as HTMLButtonElement;
const pauseButton = document.querySelector('#pause') as HTMLButtonElement;
const resetButton = document.querySelector('#reset') as HTMLButtonElement;

function setTimer(buttonPress: string) {
    setInterval(() => console.log(`${buttonPress} timer`), 1_000);
}

function clearTimer() {
    clearInterval(setTimer);
}  // TS unhappy here

function logging(buttonPress: string) {
    console.log(buttonPress);
}

//start button
startButton.addEventListener('click', () => {
    setTimer('start button');
});

//pause button
pauseButton.addEventListener('click', clearTimer);

dreamy agate
#

@chrome wave clearInterval takes a number which identifies the interval to be cleared. You're trying to pass it a function instead.

chrome wave
#

You mean I just have to pass a zero into clearInterval?

dreamy agate
#

You have to pass the value returned by setInterval to clearInterval.

#

setInterval returns a number that represents the interval that it started, you have to pass that same number to clearInterval to stop it.

chrome wave
#

But isn't that number set to setTimer?

dreamy agate
#

No?

#

setTimer is a function, it doesn't get 'set' to anything

chrome wave
#

Oh I see, I forgot I changed it into a function because it was auto starting on page load. Cheers o7