动态更新特定的 MathJax 数学项?

Dynamically update a specific MathJax math item?

如何动态更改特定 MathJax (v3.2.0) 数学项的数学字符串并更新其呈现?

下面的方法好像可以,但是感觉太低级了。我担心这种方法存在问题,或者存在更好的方法。

(async() => {
  await MathJax.typesetPromise();
  const mathDiv = document.getElementById('math');
  const [mathItem] = MathJax.startup.document.getMathItemsWithin(mathDiv);
  const mathStrings = [
    'e^{jx} = \cos x + j \sin x',
    '\hat{f}(\omega) \stackrel{\mathrm{def}}{=} \frac{1}{\sqrt{2\pi}} \int_{-\infty}^{\infty} f(t)e^{-j\omega t} dt',
  ];
  for (let i = 1; true; ++i) {
    await new Promise((resolve) => setTimeout(resolve, 2000));
    mathItem.reset();
    mathItem.math = mathStrings[i % mathStrings.length];
    mathItem.render(MathJax.startup.document);
    document.getElementById('intro').textContent = `After update #${i}:`;
  }
})();
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
<span id="intro">Before update:</span><div id="math">\[\text{placeholder}\]</div>

我想说这里的文档非常清楚:https://docs.mathjax.org/en/latest/web/typeset.html#updating-previously-typeset-content

对于尽可能最简洁的解决方案,请使用:

const mathDiv = document.getElementById('math');
await MathJax.startup.promise // make sure initial typesetting has taken place
MathJax.typesetClear([mathDiv]) // clear MathJax awareness of this element
await MathJax.typesetPromise([mathDiv]) // typeset anew

根据需要将 await 更改为 Promise 式处理,并根据需要添加 trycatch 以处理错误。