From b33187e5210e0600b1eab13e716ba65ec296d1d5 Mon Sep 17 00:00:00 2001 From: Erik Welander Date: Thu, 5 Sep 2019 19:01:16 -0700 Subject: [PATCH] Reduce setTimeout/clearTimeout calls from Delayed This reduces the time the operation I mentioned in https://github.com/codemirror/CodeMirror/pull/5992 takes to ~450ms. --- src/util/misc.js | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/util/misc.js b/src/util/misc.js index 39661eb448..a4c80ebee2 100644 --- a/src/util/misc.js +++ b/src/util/misc.js @@ -29,10 +29,27 @@ export function countColumn(string, end, tabSize, startIndex, startValue) { } export class Delayed { - constructor() {this.id = null} + constructor() { + this.id = null + this.f = null + this.time = 0 + this.handler = bind(onTimeout, this) + } + onTimeout(self) { + self.id = 0; + if (self.time < Date.now()) { + self.f() + } else { + setTimeout(self.handler, self.time - Date.now()) + } + } set(ms, f) { - clearTimeout(this.id) - this.id = setTimeout(f, ms) + this.f = f + const time = Date.now() + ms + if (!this.id || time < this.time) { + clearTimeout(this.id) + this.id = setTimeout(this.handler, ms) + } } }