diff --git a/panel/models/html.ts b/panel/models/html.ts index a844b00fe9..42744b4e8d 100644 --- a/panel/models/html.ts +++ b/panel/models/html.ts @@ -6,6 +6,7 @@ import {entries} from "@bokehjs/core/util/object" import {Markup} from "@bokehjs/models/widgets/markup" import {PanelMarkupView} from "./layout" import {serializeEvent} from "./event-to-object" +import {throttle} from "./util" import html_css from "styles/models/html.css" @@ -79,29 +80,6 @@ export function run_scripts(node: Element): void { } } -function throttle(func: Function, limit: number): any { - let lastFunc: ReturnType | undefined - let lastRan: number - - return function(...args: any) { - // @ts-ignore - const context = this - - if (!lastRan) { - func.apply(context, args) - lastRan = Date.now() - } else { - clearTimeout(lastFunc) - lastFunc = setTimeout(function() { - if ((Date.now() - lastRan) >= limit) { - func.apply(context, args) - lastRan = Date.now() - } - }, limit - (Date.now() - lastRan)) - } - } -} - export class HTMLView extends PanelMarkupView { declare model: HTML _buffer: string | null = null diff --git a/panel/models/util.ts b/panel/models/util.ts index 50a70eba6e..5cdac07a98 100644 --- a/panel/models/util.ts +++ b/panel/models/util.ts @@ -11,13 +11,27 @@ export const get = (obj: any, path: string, defaultValue: any = undefined) => { return result === undefined || result === obj ? defaultValue : result } -export function throttle(func: any, timeFrame: number) { - let lastTime: number = 0 - return function() { - const now: number = Number(new Date()) - if (now - lastTime >= timeFrame) { - func() - lastTime = now +export function throttle(func: Function, limit: number): any { + let lastRan: number = 0 + let trailingCall: ReturnType | null = null + + return function(...args: any) { + // @ts-ignore + const context = this + const now = Date.now() + if (trailingCall) { + clearTimeout(trailingCall) + } + + if ((now - lastRan) >= limit) { + func.apply(context, args) + lastRan = Date.now() + } else { + trailingCall = setTimeout(function() { + func.apply(context, args) + lastRan = Date.now() + trailingCall = null + }, limit - (now - lastRan)) } } }