0
var interval:number ;

function start() {
  interval = setInterval(function() {
    console.log(interval)
    console.log("interval...");
  }, 1000);
}

function stop() {
  console.log("stopped");
  console.log(interval)
  clearInterval(interval);
  interval = 0;
  console.log("stopped end");
}

function showInterval(){
    console.log(interval)
}

...

return(
<View>
            <Button title="startBtn" onPress={()=>{start();}}/>
            <Button title="stopBtn" onPress={()=>{stop();}}/>
            <Button title="showIntervalBtn" onPress={()=>{showInterval();}}/>
</View>
)

"I expected that when I click the stopBtn and showIntervalBtn, it would clear the interval using clearInterval(interval) and display the interval value using console.log(interval). However, the console displayed '0' and the stopBtn did not work. The start() function still displayed a unique interval value. What am I missing?"

I tried 'useState' and 'useRef'. they are good working.

RRK
  • 3
  • 3
  • Hi can you tell me more about what you want exactly, do you want interval id in showIntervalBtn function if yes then you need to remove interval = 0; from your stop function – kuuhak-u Jun 22 '23 at 15:37
  • Hello! I would like to have the interval ID stored and referenced in a different function so that I can clearInterval or showInterval using it. When using useState or useRef, the interval ID remains intact as an external state value during setInterval, allowing me to reference it in other functions for clearInterval or even logging its value using console.log. However, when I simply assign setInterval to a global variable, it seems that the interval ID doesn't get stored in the variable " var interval". it showed 0 or 'undefined' – RRK Jun 23 '23 at 09:02
  • I thought that assigning it as "interval = setInterval" would store the value in the variable "var interval", but it seems that my assumption was incorrect. What could be the issue? – RRK Jun 23 '23 at 09:03
  • its because you are setting interval = 0; in stop function just remove that and store the interval value in useState – kuuhak-u Jun 23 '23 at 13:14

0 Answers0