javascript - Violation 'setTimeout' handler took <N>ms - Stack Overflow

I am getting this console warning in my page -[Violation] 'setTimeout' handler took <N>

I am getting this console warning in my page -

[Violation] 'setTimeout' handler took <N>ms

I have checked for this issue, I got lot of answer but not able to resolve this Violation warning.

This is my useEffect code -

useEffect(() => {
        const timer = setTimeout(() => {
            const diffArr = getDiffArray(
                props.startupConfigData,
                props.runningConfigData
            );
            if (diffArr.length > 0) {
                setDiffArr(diffArr);
                setIsLoading(false);
            }
        }, 200);
        return () => clearTimeout(timer);
    });

This is my full file -

import React, { useState, useEffect } from "react";
import { diffLines, formatLines } from "./unidiff";
import { parseDiff, Diff, Hunk } from "react-diff-view";
import { getComplianceIcon, getFormattedDate } from "../mon";
import "./diff.less";
import "react-diff-view/style/index.css";

/**
 * This constant is used for chunking.
 * A value of 3000 takes ~ 15 secs to show the diff for real data
 * A value of 2000 takes ~ 12 secs to show the diff for real data
 */
const THRESHOLD = 2000; //changing this is reflecting in response time, need to check

const DiffViewer = props => {
    const { startUpFile, runningFile, showLoader, pareWith } = props;
    const [diffArr, setDiffArr] = useState([]);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const timer = setTimeout(() => {
            const diffArr = getDiffArray(
                props.startupConfigData,
                props.runningConfigData
            );
            if (diffArr.length > 0) {
                setDiffArr(diffArr);
                setIsLoading(false);
            }
        }, 200);
        return () => clearTimeout(timer);
    });

    /**
     * Returns an array of differences in the unidiff format
     *
     * @param {string} oldLongText - the old string to pare
     * @param {string} newLongText - the new string to pare
     * @returns {Array} - the array having the diff objects
     */
    const getDiffArray = (oldLongText = "", newLongText = "") => {
        if (oldLongText !== newLongText) {
            const oldTextChunks = getChunkedLinesOfText(oldLongText, THRESHOLD);
            const newTextChunks = getChunkedLinesOfText(newLongText, THRESHOLD);
            const chunkMaxLen = Math.max(oldTextChunks.length, newTextChunks.length);
            const zipChunks = (_, i) => [
                oldTextChunks[i] || "",
                newTextChunks[i] || ""
            ];
            const unmodDiffContext = chunkMaxLen > 1 ? 3 : 500;
            return Array.from({ length: chunkMaxLen }, zipChunks).reduce(
                (res, [oldText, newText], idx) => {
                    const diffText = puteDiff(oldText, newText, unmodDiffContext);
                    if (diffText) {
                        const maxLenOfText =
                            idx * THRESHOLD +
                            Math.max(oldText.split("\n").length, newText.split("\n").length);
                        res.push({ diffText, start: idx * THRESHOLD, end: maxLenOfText });
                    }
                    return res;
                },
                []
            );
        }
        return [];
    };

    /**
     * Splits input text into chunks of specified size
     *
     * @param {string} text - takes the input text and splits it into chunks
     * @param {number} threshold - takes a threshold which is the chunk size
     * @returns {Array} - returns an array of strings as specified by the chunk size
     */
    const getChunkedLinesOfText = (text = "", threshold = 3000) => {
        const totalLines = (typeof text === "string" && text.split("\n")) || [];
        if (threshold > 0 && totalLines.length > threshold) {
            const chunks = Math.ceil(totalLines.length / threshold);
            const chunkArray = (_, idx) =>
                totalLines
                    .slice(idx * threshold, idx * threshold + threshold)
                    .join("\n");
            return Array.from({ length: chunks }, chunkArray);
        }
        return [text];
    };

    const puteDiff = (oldText = "", newText = "", unmodDiffContext = 3) => {
        return formatLines(diffLines(oldText, newText), {
            context: unmodDiffContext
        });
    };

    const renderFile = (
        { oldRevision, newRevision, type, hunks },
        start,
        end,
        isFirstDiff
    ) => {
        const separator = `${i18n.diff_showing_lines} ${start} - ${end}`;
        return (
            <div
                className="diff-div margin-left-5px"
                key={oldRevision + `${separator}` - +newRevision}
            >
                {!isFirstDiff && <div className="diff-separator">{separator}</div>}
                <Diff
                    key={oldRevision + `${separator}` - +newRevision}
                    viewType="split"
                    diffType={type}
                    hunks={hunks}
                >
                    {hunks => hunks.map(hunk => <Hunk key={hunk.content} hunk={hunk} />)}
                </Diff>
            </div>
        );
    };

    /**
     * Get text based on selection - startup/running
     */
    const getStartupText = () => {
        if (pareWith == undefined || pareWith === "startup") {
            return i18n.label_startup_configuration;
        } else {
            return i18n.label_running_configuration;
        }
    };

    const statusDisplayDetails = getComplianceIcon("COMPLIANT", true);
    const DiffData_Loading = () => {
        let loderLabel;
        let loderLabelExtraTime = i18n.take_while_text;
        if (props.runningFile)
            loderLabel =
                props.runningFile.totalNoOfLines < 5000
                    ? "Loading..."
                    : loderLabelExtraTime;
        return (
            <div className="loading-icon">
                <DnxLoader color="#026E97" size="54" label={loderLabel} />
            </div>
        );
    };

    /**
     * Function returns the DnxBanner information text for diff Position Mismatch
     */
    const _diffPositionMismatchInfoText = () => {
        const informationConfig = {
            message: i18n.diff_postion_mismatch_info,
            type: "information"
        };
        return (
            <div className="margin-5px">
                <DnxBanner name="banner-loading" config={informationConfig}></DnxBanner>
            </div>
        );
    };

    /**
     * return function
     */
    return (
        <div className="">
            <div>
                {startUpFile && runningFile ? (
                    <div>
                        {showLoader ? (
                            DiffData_Loading()
                        ) : (
                            <div>
                                <div className="flex margin-left-5px">
                                    <div className="startup-text">
                                        {getStartupText()} ({startUpFile.totalNoOfLines}{" "}
                                        {i18n.label_lines}) -{" "}
                                        {getFormattedDate(startUpFile.createdTime)}
                                    </div>
                                    <div className="running-text">
                                        {i18n.label_running_configuration} (
                                        {runningFile.totalNoOfLines} {i18n.label_lines}) -{" "}
                                        {getFormattedDate(runningFile.createdTime)}
                                    </div>
                                </div>
                                {diffArr &&
                                props.startupConfigData !== props.runningConfigData ? (
                                    <div>
                                        {isLoading && DiffData_Loading()}
                                        {!isLoading && (
                                            <div>
                                                {diffArr.map(({ diffText, start, end }, idx) =>
                                                    parseDiff(diffText, { nearbySequences: "zip" }).map(
                                                        file => renderFile(file, start, end, idx === 0)
                                                    )
                                                )}
                                            </div>
                                        )}
                                    </div>
                                ) : (
                                    <div className="div-margin-diff">
                                        {statusDisplayDetails}
                                        <span>
                                            {pareWith === "running"
                                                ? i18n.label_running_config_pliant
                                                : i18n.label_running_startup_config_pliant}
                                        </span>
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                ) : (
                    <div className="div-margin-diff">
                        <span>{i18n.label_running_config_not_available}</span>
                    </div>
                )}
            </div>
            {_diffPositionMismatchInfoText()}
        </div>
    );
};

export default DiffViewer;

Please guide me what should be changed.

I am getting this console warning in my page -

[Violation] 'setTimeout' handler took <N>ms

I have checked for this issue, I got lot of answer but not able to resolve this Violation warning.

This is my useEffect code -

useEffect(() => {
        const timer = setTimeout(() => {
            const diffArr = getDiffArray(
                props.startupConfigData,
                props.runningConfigData
            );
            if (diffArr.length > 0) {
                setDiffArr(diffArr);
                setIsLoading(false);
            }
        }, 200);
        return () => clearTimeout(timer);
    });

This is my full file -

import React, { useState, useEffect } from "react";
import { diffLines, formatLines } from "./unidiff";
import { parseDiff, Diff, Hunk } from "react-diff-view";
import { getComplianceIcon, getFormattedDate } from "../mon";
import "./diff.less";
import "react-diff-view/style/index.css";

/**
 * This constant is used for chunking.
 * A value of 3000 takes ~ 15 secs to show the diff for real data
 * A value of 2000 takes ~ 12 secs to show the diff for real data
 */
const THRESHOLD = 2000; //changing this is reflecting in response time, need to check

const DiffViewer = props => {
    const { startUpFile, runningFile, showLoader, pareWith } = props;
    const [diffArr, setDiffArr] = useState([]);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const timer = setTimeout(() => {
            const diffArr = getDiffArray(
                props.startupConfigData,
                props.runningConfigData
            );
            if (diffArr.length > 0) {
                setDiffArr(diffArr);
                setIsLoading(false);
            }
        }, 200);
        return () => clearTimeout(timer);
    });

    /**
     * Returns an array of differences in the unidiff format
     *
     * @param {string} oldLongText - the old string to pare
     * @param {string} newLongText - the new string to pare
     * @returns {Array} - the array having the diff objects
     */
    const getDiffArray = (oldLongText = "", newLongText = "") => {
        if (oldLongText !== newLongText) {
            const oldTextChunks = getChunkedLinesOfText(oldLongText, THRESHOLD);
            const newTextChunks = getChunkedLinesOfText(newLongText, THRESHOLD);
            const chunkMaxLen = Math.max(oldTextChunks.length, newTextChunks.length);
            const zipChunks = (_, i) => [
                oldTextChunks[i] || "",
                newTextChunks[i] || ""
            ];
            const unmodDiffContext = chunkMaxLen > 1 ? 3 : 500;
            return Array.from({ length: chunkMaxLen }, zipChunks).reduce(
                (res, [oldText, newText], idx) => {
                    const diffText = puteDiff(oldText, newText, unmodDiffContext);
                    if (diffText) {
                        const maxLenOfText =
                            idx * THRESHOLD +
                            Math.max(oldText.split("\n").length, newText.split("\n").length);
                        res.push({ diffText, start: idx * THRESHOLD, end: maxLenOfText });
                    }
                    return res;
                },
                []
            );
        }
        return [];
    };

    /**
     * Splits input text into chunks of specified size
     *
     * @param {string} text - takes the input text and splits it into chunks
     * @param {number} threshold - takes a threshold which is the chunk size
     * @returns {Array} - returns an array of strings as specified by the chunk size
     */
    const getChunkedLinesOfText = (text = "", threshold = 3000) => {
        const totalLines = (typeof text === "string" && text.split("\n")) || [];
        if (threshold > 0 && totalLines.length > threshold) {
            const chunks = Math.ceil(totalLines.length / threshold);
            const chunkArray = (_, idx) =>
                totalLines
                    .slice(idx * threshold, idx * threshold + threshold)
                    .join("\n");
            return Array.from({ length: chunks }, chunkArray);
        }
        return [text];
    };

    const puteDiff = (oldText = "", newText = "", unmodDiffContext = 3) => {
        return formatLines(diffLines(oldText, newText), {
            context: unmodDiffContext
        });
    };

    const renderFile = (
        { oldRevision, newRevision, type, hunks },
        start,
        end,
        isFirstDiff
    ) => {
        const separator = `${i18n.diff_showing_lines} ${start} - ${end}`;
        return (
            <div
                className="diff-div margin-left-5px"
                key={oldRevision + `${separator}` - +newRevision}
            >
                {!isFirstDiff && <div className="diff-separator">{separator}</div>}
                <Diff
                    key={oldRevision + `${separator}` - +newRevision}
                    viewType="split"
                    diffType={type}
                    hunks={hunks}
                >
                    {hunks => hunks.map(hunk => <Hunk key={hunk.content} hunk={hunk} />)}
                </Diff>
            </div>
        );
    };

    /**
     * Get text based on selection - startup/running
     */
    const getStartupText = () => {
        if (pareWith == undefined || pareWith === "startup") {
            return i18n.label_startup_configuration;
        } else {
            return i18n.label_running_configuration;
        }
    };

    const statusDisplayDetails = getComplianceIcon("COMPLIANT", true);
    const DiffData_Loading = () => {
        let loderLabel;
        let loderLabelExtraTime = i18n.take_while_text;
        if (props.runningFile)
            loderLabel =
                props.runningFile.totalNoOfLines < 5000
                    ? "Loading..."
                    : loderLabelExtraTime;
        return (
            <div className="loading-icon">
                <DnxLoader color="#026E97" size="54" label={loderLabel} />
            </div>
        );
    };

    /**
     * Function returns the DnxBanner information text for diff Position Mismatch
     */
    const _diffPositionMismatchInfoText = () => {
        const informationConfig = {
            message: i18n.diff_postion_mismatch_info,
            type: "information"
        };
        return (
            <div className="margin-5px">
                <DnxBanner name="banner-loading" config={informationConfig}></DnxBanner>
            </div>
        );
    };

    /**
     * return function
     */
    return (
        <div className="">
            <div>
                {startUpFile && runningFile ? (
                    <div>
                        {showLoader ? (
                            DiffData_Loading()
                        ) : (
                            <div>
                                <div className="flex margin-left-5px">
                                    <div className="startup-text">
                                        {getStartupText()} ({startUpFile.totalNoOfLines}{" "}
                                        {i18n.label_lines}) -{" "}
                                        {getFormattedDate(startUpFile.createdTime)}
                                    </div>
                                    <div className="running-text">
                                        {i18n.label_running_configuration} (
                                        {runningFile.totalNoOfLines} {i18n.label_lines}) -{" "}
                                        {getFormattedDate(runningFile.createdTime)}
                                    </div>
                                </div>
                                {diffArr &&
                                props.startupConfigData !== props.runningConfigData ? (
                                    <div>
                                        {isLoading && DiffData_Loading()}
                                        {!isLoading && (
                                            <div>
                                                {diffArr.map(({ diffText, start, end }, idx) =>
                                                    parseDiff(diffText, { nearbySequences: "zip" }).map(
                                                        file => renderFile(file, start, end, idx === 0)
                                                    )
                                                )}
                                            </div>
                                        )}
                                    </div>
                                ) : (
                                    <div className="div-margin-diff">
                                        {statusDisplayDetails}
                                        <span>
                                            {pareWith === "running"
                                                ? i18n.label_running_config_pliant
                                                : i18n.label_running_startup_config_pliant}
                                        </span>
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                ) : (
                    <div className="div-margin-diff">
                        <span>{i18n.label_running_config_not_available}</span>
                    </div>
                )}
            </div>
            {_diffPositionMismatchInfoText()}
        </div>
    );
};

export default DiffViewer;

Please guide me what should be changed.

Share Improve this question asked Jul 6, 2020 at 10:16 FrontEnd ExpertFrontEnd Expert 5,81510 gold badges63 silver badges100 bronze badges 1
  • Have you had any luck to finding a solution to this? I am running into the same issue. – edjm Commented Oct 20, 2020 at 14:28
Add a ment  | 

1 Answer 1

Reset to default 2

It's the browser trying to tell you that a handler function (a piece of javascript code that's executed on the main thread in response to an event happening) is taking longer than it should and probably posing a potential blocking to the event loop.

This idea of avoiding blocking of the event loop is the heart of writing performant JS applications.

The warning itself won't harm your application now, but it could cause your script to block if you didn't care to the amount of synchronous work you are putting in a "handler" function.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745424609a4627116.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信