断念 2022-05-04 13:56:07
贴个完整的
<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <input type="text" /> <script> function throttle(fn, delay) { let timer; let isFirstCall = true; return function (...args) { const ctx = this; if (isFirstCall) { isFirstCall = false; fn.apply(ctx, args); return; } if (timer) return; timer = setTimeout(() => { timer = null; fn.apply(ctx, args); }, delay); }; } function input(e) { if (e.target.composing) { return; } console.log(e.target.value); } function onCompositionStart(e) { e.target.composing = true; } function onCompositionEnd(e) { const event = new CustomEvent("input"); e.target.composing = false; e.target.dispatchEvent(event); } function onCompositionUpdate(e) { console.log(e.target.value); } const inputEle = document.getElementById("spell_input"); inputEle.addEventListener("input", throttle(input, 1000)); inputEle.addEventListener("compositionstart", onCompositionStart); inputEle.addEventListener("compositionend", onCompositionEnd); inputEle.addEventListener("compositionupdate", onCompositionUpdate); </script> </body> </html>
throttle这个是节流
- 共 1 页
- 1
是否可以这样认为,同步异步是两者的通信方式,CPU 同 I/O 或数据库。阻塞非阻塞是个体的工作方式,进程的单线程、多线程。单线程工作方式的进程就是阻塞的,多线程工作方式的进程就是非阻塞的。
NodeJS 应该是利用了事件循环既实现了两者间的异步通信,又解决了单线程的阻塞难题。(对比时分复用,将单线程按事件划分成虚拟的多线程,但是对CPU密集程序来说它还是阻塞的)
从 Promise 来看 JavaScript 中的 Event Loop、Tasks 和 Microtasks