为什么可视化有延迟? [英] Why there is a delay on visualization?

查看:31
本文介绍了为什么可视化有延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个排序可视化.我从一个简单的冒泡排序开始.当我对一个小数组进行排序时,一切都很好,无论速度如何,可视化看起来都不错,但是当我可视化一个大数组时,会出现延迟,并且可视化似乎提前几步开始,并且没有显示一些第一步.为什么会这样?

这是我的代码:

import React, { useContext, useState, useEffect } from 'react';const NUMBER_OF_ELEMENTS = 10;const DEFAULT_COLOR = '黑色';const COMPARE_COLOR = '暗红色';const DONE_COLOR = '绿色';常量速度 = 150;const randomIntFromInterval = (min, max) =>{返回 Math.floor(Math.random() * (max - min + 1) + min);}const Dummy = () =>{const [arr, setArr] = useState([]);const [numberOfElements, setNumberOfElements] = useState(NUMBER_OF_ELEMENTS);const timeout_id = [];useEffect(() => {生成数组();}, []);const reset = () =>{重置颜色();生成数组();}const generateArray = () =>{const arr1 = [];for(let i = 0; i {const arrayBars = document.getElementsByClassName('array-bar');for(let i = 0; i {让 i, j, temp, 交换, 延迟 = 1;for(i = 0; i {const arrayBars = document.getElementsByClassName('array-bar');const id = setTimeout(() => {const barOneHeight = arrayBars[one].style.height;const barTwoHeight = arrayBars[two].style.height;arrayBars[two].style.height = `${barOneHeight}`;arrayBars[one].style.height = `${barTwoHeight}`;}, SPEED * 延迟);timeout_id.push(id);}const createColor =(索引,颜色,延迟)=>{const arrayBars = document.getElementsByClassName('array-bar');const id = setTimeout(() => {for(let i = 0; i {气泡排序(arr,arr.length);}const handlerRange = (e) =>{setNumberOfElements(e.target.value);}const stopTimeOuts =() =>{for(let i = 0; i < timeout_id.length; i++) {clearTimeout(timeout_id[i]);}}返回 (<div><div className="array-container">{arr.map((value, idx) => (<div className="array-bar"键={idx}风格={{背景颜色:DEFAULT_COLOR,高度:`${value}px`,宽度:`${100/arr.length}%`,显示:'内联块',边距:'0 1px'}}>

))}

<div className="buttons-container"><button onClick={() =>handleSort(arr)}>Sort!</button><button onClick={() =>reset()}>重置</button><button onClick={() =>stopTimeOuts()}>停止!</button>

<div className="slider-container">1<输入类型=范围"分钟=1"最大=100"onChange={(e) =>handlerRange(e)}类名=滑块"id =我的范围"/>100

{元素数量}

);}导出默认虚拟;

编辑:我不知道为什么,但似乎有时会发生延迟,有时不会.目前我仍然不知道这是为什么以及如何处理.

解决方案

当 React 中出现性能问题时,几乎总是与组件被多次渲染有关.尝试像这样改变 useEffect:

useEffect(() => {生成数组();}, [NUMBER_OF_ELEMENTS]);

I am building a sorting visualization. I started with a simple bubble sort. When I sort a small array everything is fine and the visualization looks good no matter the speed, but when I visualize a large array there is a delay and the visualization seems to start a few steps ahead and not showing some of the first steps. Why is it happening?

This is my Code:

import React, { useContext, useState, useEffect } from 'react';

const NUMBER_OF_ELEMENTS = 10;

const DEFAULT_COLOR = 'black';
const COMPARE_COLOR = 'darkred';
const DONE_COLOR = 'green';

const SPEED = 150;

const randomIntFromInterval = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

const Dummy = () => {
    const [arr, setArr] = useState([]);
    const [numberOfElements, setNumberOfElements] = useState(NUMBER_OF_ELEMENTS);

    const timeout_id = [];

    useEffect(() => {
        generateArray();
    }, []);

    const reset = () => {
        resetColors();
        generateArray();
    }

    const generateArray = () => {
        const arr1 = [];
        for(let i = 0; i < numberOfElements; i++)
        {
            arr1[i] = randomIntFromInterval(5, 100);
        }
        console.log(arr1);
        setArr(arr1);
    }

    const resetColors = () => {
        const arrayBars = document.getElementsByClassName('array-bar');
        for(let i = 0; i < arrayBars.length; i++) {
            arrayBars[i].style.backgroundColor = DEFAULT_COLOR;
        }
    }

    const bubbleSort = (arr, n) => {
        let i, j, temp, swapped, delay = 1;
        for(i = 0; i < n - 1; i++) 
        {
            swapped = false;
            for(j = 0; j < n - i - 1; j++) 
            {
                createColor([j, j + 1], COMPARE_COLOR,  delay++);
                if(arr[j] > arr[j + 1]) 
                {
                    // swap arr[j] and arr[j+1] 
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                    createAnimation(j, j + 1, delay++);
                }
                createColor([j, j + 1], DEFAULT_COLOR, delay++);
            }
            createColor([n - i - 1], DONE_COLOR, delay++);

            // If no two elements were  
            // swapped by inner loop, then break 
            if(swapped === false) break;
        }

        const leftovers = [];
        for(let k = 0; k < n - i - 1; k++) {
            leftovers.push(k);
        }

        createColor(leftovers, DONE_COLOR, delay++);
    }

    const createAnimation = (one, two, delay) => {
        const arrayBars = document.getElementsByClassName('array-bar');
        const id = setTimeout(() => {
            const barOneHeight = arrayBars[one].style.height;
            const barTwoHeight = arrayBars[two].style.height;
            arrayBars[two].style.height = `${barOneHeight}`;
            arrayBars[one].style.height = `${barTwoHeight}`;
        }, SPEED * delay);
        timeout_id.push(id);
    }

    const createColor = (indexes, color, delay) => {
        const arrayBars = document.getElementsByClassName('array-bar');
        const id = setTimeout(() => {
            for(let i = 0; i < indexes.length; i++) {
                arrayBars[indexes[i]].style.backgroundColor = color;
            }
        }, SPEED * delay);
        timeout_id.push(id);
    }

    const handleSort = (arr) => {
        bubbleSort(arr, arr.length);
    }

    const handlerRange = (e) => {
        setNumberOfElements(e.target.value);
    }

    const stopTimeOuts =() => {
        for(let i = 0; i < timeout_id.length; i++) {
            clearTimeout(timeout_id[i]);
        }
    }

    return (
        <div>
            <div className="array-container">
                {arr.map((value, idx) => (
                    <div className="array-bar"
                         key={idx}
                         style={{
                            backgroundColor: DEFAULT_COLOR,
                            height: `${value}px`,
                            width: `${100 / arr.length}%`,
                            display: 'inline-block',
                            margin: '0 1px'
                         }}>
                    </div>
                ))}
            </div>

            <div className="buttons-container">
                <button onClick={() => handleSort(arr)}>Sort!</button>
                <button onClick={() => reset()}>Reset</button>
                <button onClick={() => stopTimeOuts()}>Stop!</button>
            </div>

            <div className="slider-container">
                1
                <input type="range" 
                       min="1" 
                       max="100" 
                       onChange={(e) => handlerRange(e)} 
                       className="slider" 
                       id="myRange" 
                />
                100
            </div>
            {numberOfElements}

        </div>
    );
}

export default Dummy;

EDIT: I don't know why but it seems that there are times that the delay occurs and there are times that it isn't. For now I still don't know why and how to handle this.

解决方案

Almost always when there are performance issues in React it has to do with component being rendered multiple times. Try to change useEffect like this:

useEffect(() => {
        generateArray();
}, [NUMBER_OF_ELEMENTS]);

这篇关于为什么可视化有延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆