JSFiddle - React, Tailwind, and code Playground

HTML

<body>
  <div class="container"><span>测试test testa 测试test testab 测试test testabc 测试test testabcd 测试test</span></div>
</body>

CSS

.container {
  text-align: left;
  width: 300px;
  background: gray;
  font-size: 20px;
  line-height: 24px;
}

JavaScript

const callbacks = [];
let pending = false;
let timerFunc = null;

function flushCallbacks() {
    pending = false;
    const copies = callbacks.slice(0);
    callbacks.length = 0;
    for(let i = 0; i < copies.length; i += 1) {
        copies[i]();
    }
}

const p = Promise.resolve();
timerFunc = () => {
    p.then(flushCallbacks);
    setTimeout(() => {});
}

function nextTick(callback) {
    let _resolve = null;
    callbacks.push(() => {
        if (callback) {
            try {
                callback()
            } catch (e) {
                console.warn('nextTick error: ', e);
            }
        } else if (_resolve) {
            _resolve();
        }
    })
    if (!pending) {
        pending = true;
        timerFunc();
    }

    if (!callback) {
        return new Promise((resolve) => {
            _resolve = resolve;
        })
    }
}

let offCtx = null;

async function adjustFontSizeLoop(lineNum, containerEle, step = 1, minFontSize = 8, adjustLineHeight = false) {
  let isOverflow = false;
  const computedStyle = getComputedStyle(containerEle);

  if (!/^\d+/.test(computedStyle.lineHeight)) {
    throw new Error('container\'s lineHeight must be a exact value!');
  }

  let lineHeight = Number(computedStyle.lineHeight.slice(0, -2));
  let fontSize = Number(computedStyle.fontSize.slice(0, -2));
  if (containerEle.scrollHeight <= Math.ceil(lineHeight * lineNum)) {
    return;
  }

  const textBody = containerEle.childNodes[0];

  if (!offCtx) {
    offCtx = document.createElement('canvas').getContext('2d');
  }
  const { fontFamily } = computedStyle;
  offCtx.font = `${fontSize}px ${fontFamily}`;
  const { width: measuredWidth } = offCtx.measureText(textBody.innerText);
  if (containerEle.offsetWidth * lineNum >= measuredWidth) {
    return;
  }

  let firstTransFontSize = fontSize;
  let firstTransLineHeight = lineHeight;
  firstTransFontSize = Math.max(
    minFontSize,
    fontSize * (containerEle.offsetWidth * lineNum / measuredWidth)
  );
 ...