实现一个倒计时组件

189 阅读1分钟

主要是使用web worker 开启一个进程,从而在主进程阻塞是不会影响倒计时,同时提供倒计时的回调函数函数,

import React, { useState, useEffect } from 'react';
function Countdown({ initialTime, callback = function () { console.log('not found callback') } }) {
    const [timeLeft, setTimeLeft] = useState(initialTime);
    useEffect(() => {
        const workerCode = `
        let time = ${initialTime};
        const intervalId = setInterval(() => {
            time -= 1;
            postMessage(time);
        }, 1000);
        setTimeout(() => {
            clearInterval(intervalId);
            postMessage(0);
        }, ${initialTime} * 1000);`
        const blob = new Blob([workerCode], { type: 'text/javascript' });
        const worker = new Worker(URL.createObjectURL(blob));
        worker.onmessage = (event) => {
            setTimeLeft(event.data);
        };
        return () => {
            worker.terminate();
        };
    }, [initialTime]);
    useEffect(() => {
        if (timeLeft === 0) {
            callback()
        }
    }, [timeLeft])
    return (
        <div>
            <h1>Countdown: {timeLeft} seconds</h1>
        </div>
    );
}