Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
usando setInterval y clearInterval para cambiar el contador en la aplicación de reacción

Estoy tratando de crear una aplicación con una 'bañera' y 2 botones. La bañera tiene 5 niveles de agua. Cuando hace clic en el primer botón, la tina llena un nivel cada 2 segundos hasta llegar a 5. El otro botón drena la tina hasta el nivel 0. Las funciones de aumentar el nivel del agua y disminuir el nivel del agua solo se activan una vez y no estoy seguro de por qué.

 import React, { useState } from "react"; const App = () => { const [waterLevel, setWaterLevel] = useState(0); let fillTub; let drainTub; const increaseWaterLevel = () => { if (waterLevel < 5) { const newWaterLevel = waterLevel + 1; setWaterLevel(newWaterLevel); } else { clearInterval(fillTub); } }; const decreaseWaterLevel = () => { if (waterLevel > 0) { const newWaterLevel = waterLevel - 1; setWaterLevel(newWaterLevel); } else { clearInterval(fillTub); } }; return ( <div> <div>Bathtub</div> <button onClick={() => { fillTub = window.setInterval(increaseWaterLevel, 2000); }} > increaseWaterLevel </button> <button onClick={() => { drainTub = window.setInterval(decreaseWaterLevel, 2000); }} > decreaseWaterLevel </button> </div> ); }; export default App;

actualizar el contador funciona pero no se detiene y el nivel del agua permanece en 0. ¿Qué estoy haciendo mal?

 import React, { useState } from "react"; const App = () => { const [waterLevel, setWaterLevel] = useState(0); const [intervalId, setIntervalId] = useState(0); const increaseWaterLevel = () => { const newWaterLevel = setInterval(() => { if (waterLevel > 4) { clearInterval(intervalId); } else { setWaterLevel((prevWaterLevel) => prevWaterLevel + 1); } }, 2000); setIntervalId(newWaterLevel); }; const decreaseWaterLevel = () => { const newWaterLevel = setInterval(() => { if (waterLevel > 0) { setWaterLevel((prevWaterLevel) => prevWaterLevel - 1); } else { clearInterval(intervalId); } }, 2000); setIntervalId(newWaterLevel); }; return ( <div> <div>Bathtub</div> <button onClick={increaseWaterLevel}>increaseWaterLevel</button> <button onClick={decreaseWaterLevel}>decreaseWaterLevel</button> </div> ); }; export default App;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Permítanme decir primero que comencé a aprender a reaccionar como hace 1 semana y todavía tengo algunas dudas y este código puede ser realmente malo incluso si funciona, pero aún quiero ayudar, así que este es el código.

El principal problema aquí es que la función useState es una función asíncrona y no actualiza en tiempo real su variable, por lo que en este caso no funcionará verificar el valor de waterLevel sin useEffect .

 import React, { useState, useEffect } from "react"; const App = () => { const [waterLevel, setWaterLevel] = useState(0); const [actionType, setActionType] = useState(); useEffect(() => { const interval = setInterval(() => { if (actionType == "increase" && waterLevel < 5) setWaterLevel(waterLevel + 1); if (actionType == "decrease" && waterLevel > 0) setWaterLevel(waterLevel - 1); }, 2000); return () => clearInterval(interval); }, [actionType, waterLevel]); return ( <div> <div>Bathtub</div> <button onClick={() => setActionType("increase")}> increaseWaterLevel </button> <button onClick={() => setActionType("decrease")}> decreaseWaterLevel </button> <h1>{waterLevel}</h1> </div> ); }; export default App;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!