Duplicated setTimeout

Viewed 27

When I press the "Buy" button sometimes its grow up correctly and sometimes its just count by 2 clicks. Why this is happening? I am using UseState for change the values and setTimeout for passive increment, so when I press the Buy button its remove the older setTimeout and add a new with the new values.

import Head from 'next/head';
import styles from '../styles/Home.module.css';
import React, { useState, useEffect } from 'react';

var increment = 1000;
var preco = 10;
var total = 0;
function Master() {
  const [points, setpoints] = useState(0);
  const [Ppoints, setPpoints] = useState(0);
  total = points;
  function addpoints() {
    setpoints((points) => points + 1);
    window.clearTimeout(timer);
  }
  function addPpoints() {
    setpoints((points) => points + Ppoints);
  }
  //passive addiction
  let timer = setTimeout(addPpoints, increment);
  function passive() {
    if (total >= preco) {
      setPpoints(Ppoints + 0.5);
      setpoints(points - preco);
      preco += 10;
      window.clearTimeout(timer);
    }
  }
  return (
    <>
      <h1>{total}</h1>
      <button onClick={addpoints}>adicionar</button>
      <h1>Price: {preco}</h1>
      <button onClick={passive}>Buy</button>
    </>
  );
}

export default function Home() {
  return (
    <>
      <Master />
    </>
  );
}
0 Answers
Related