Skip to content

Instantly share code, notes, and snippets.

@hungdev
Last active December 24, 2024 15:00
Show Gist options
  • Save hungdev/4168253a7bcc37dbd696f5925eadfced to your computer and use it in GitHub Desktop.
Save hungdev/4168253a7bcc37dbd696f5925eadfced to your computer and use it in GitHub Desktop.
c
// App.js hoặc component của bạn
import React, { useState, useRef } from "react";
// import FunctionQueue from "./FunctionQueue"; // Import FunctionQueue
import { debounce } from "perfect-debounce";

// const queue = new FunctionQueue();

const App = () => {
  const [count, setCount] = useState(0);
  const debouncedRef = useRef(null);

  // // Function bình thường
  // const normalFunction = async () => {
  //   console.log("Running normal function...");
  //   // await new Promise((resolve) => setTimeout(resolve, 1000)); // Giả lập thời gian xử lý
  //   console.log("Normal function done");
  //   // setCount(count + 1);
  // };

  // // Function debounce
  // const debounceFunction = async () => {
  //   console.log("Running debounce function...");
  //   // await new Promise((resolve) => setTimeout(resolve, 2000)); // Giả lập thời gian xử lý debounce
  //   console.log("Debounce function done");
  // };

  // Gọi function bình thường và debounce, thêm vào queue
  const handleNormalClick = () => {
    // queue.addFunctionToQueue(normalFunction);
    console.log("Normal function done");
  };

  const handleDebounceClick = () => {
    // queue.addFunctionToQueue(debounceFunction);
    debouncedRef.current = debounce(async () => {
      setCount(count + 1);
      console.log("Debounce function done");
    }, 500);
  };

  return (
    <div>
      <button onClick={handleNormalClick}>Run Normal Function</button>
      <button onClick={handleDebounceClick}>Run Debounce Function</button>
      <div>Count: {count}</div>
    </div>
  );
};

export default App;
@ngobach
Copy link

ngobach commented Dec 24, 2024

import React, { useState, useRef } from "react";
import { debounce } from "perfect-debounce";

const App = () => {
  const [count, setCount] = useState(0);
  const debouncedIncrease = useRef(
    debounce(async () => {
      await new Promise((resolve) => setTimeout(resolve, 100));
      setCount((prev) => prev + 1);
      console.log("Quantity updated");
    }, 1000)
  ).current;
  const lastDebouncedIncrease = useRef(null);

  const handleIncrease = () => {
    lastDebouncedIncrease.current = debouncedIncrease();
  };

  const handleCommit = async () => {
    await lastDebouncedIncrease.current;
    console.log("Committing");
  };

  return (
    <div>
      <button onClick={handleIncrease}>Increase</button>
      <button onClick={handleCommit}>Commit</button>
      <div>Count: {count}</div>
    </div>
  );
};

export default App;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment