Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save teramotodaiki/71f3fdf2970778452e58f414d6b8e110 to your computer and use it in GitHub Desktop.
Save teramotodaiki/71f3fdf2970778452e58f414d6b8e110 to your computer and use it in GitHub Desktop.
React.useEffect(() => {
function onChange(instance: CodeMirror.Editor) {
if (!definition) return; // 定義ファイルのロードが済んでいない
const age = ++ageRef.current; // 前回までの処理をキャンセルさせる
const makeWidget = makeWidgetRoutine(instance, definition, hint);
const widgets = [] as WidgetBase[];
(function step() {
window.requestIdleCallback(
deadline => {
if (age !== ageRef.current) {
return; // キャンセルされた
}
const limit = 100; // Widget の上限
for (let _ = 0; _ < 100; _++) {
const { value, done } = makeWidget.next();
value && widgets.push(value);
if (done || deadline.didTimeout || widgets.length >= limit) {
// 描画処理は最後に一気にやった方が体感的に良い
widgetsRef.current.forEach(e =>
e.parentElement?.removeChild(e)
); // 前回の Widget を削除
widgetsRef.current = widgets.map(createWidget); // Widget を作成
return;
}
if (deadline.timeRemaining() < 5) {
break; // 猶予がなくなったので処理を一時中断
}
}
step(); // 次の処理をキューイング
},
{ timeout: 1000 }
);
})();
}
if (props.codemirror) {
onChange(props.codemirror);
}
props.codemirror?.on('change', onChange);
return () => {
props.codemirror?.off('change', onChange);
};
}, [props.codemirror, definition]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment