J
J
justifycontent2021-05-16 06:56:03
React
justifycontent, 2021-05-16 06:56:03

Why timerRef is 6?

There is an application that can add a number that is 1 more than the last one in the list.
The number can be added manually, or you can click on the start button, then the start button handler will automatically add the number to the list via setInterval. But why is timerRef.current always equal to 6? Where is this 6 from? timerRef.current stores setInterval.

import React, { useEffect } from 'react';

const List = () => {
  const [numbers, setNumbers] = React.useState([1, 2, 3, 4]);
  const ulRef = React.useRef();
  const timerRef = React.useRef();

  React.useEffect(() => {
    ulRef.current.addEventListener('scroll', handleScroll)
  }, [])

  const handleScroll = () => {
    console.log('Произошел scroll');
  }

  const removeScroll = () => {
    console.log(ulRef)
    ulRef.current.removeEventListener('scroll', handleScroll);
  }

  const addNumber = () => {
    setNumbers(prev =>[...prev, prev[prev.length - 1] + 1]);
  }

  const start = () => {
    timerRef.current = setInterval(addNumber, 1000);
  }

  const stop = () => {
    clearInterval(timerRef.current);
  }

  useEffect(() => {
    console.log(timerRef.current)
  })


  return (
    <>
      <ul ref={ulRef}>
        {numbers.map((num, i) => <li key={`${num}_${i}`}>{num}</li>)}
      </ul>
      <button onClick={addNumber}>✅ Добавить число</button>
      <button onClick={removeScroll}>❎ Не следить</button>
      <button onClick={start}>▶️ Старт</button>
      <button onClick={stop}>⏹ Стоп</button>
    </>
  )
}

export default List;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Confy, 2021-05-16
@justifycontent

Calling setTimeout, like setInterval, returns a timer identifier that can be used to cancel (disable) the execution of a function after the timer with clearTimeout(id)- for setTimeoutand clearIntervalfor setInterval
More details
Why 6?
In browsers, timer identifiers are numeric, unique for each timer, and go in order starting from 1. This means that before timer number 6, 5 more intervals / timers were launched by some scripts.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question