Skip to content

Commit

Permalink
Combine throttle implementations (#7480)
Browse files Browse the repository at this point in the history
  • Loading branch information
philippjfr authored Nov 11, 2024
1 parent bddcf35 commit 89b0bc6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 30 deletions.
24 changes: 1 addition & 23 deletions panel/models/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -79,29 +80,6 @@ export function run_scripts(node: Element): void {
}
}

function throttle(func: Function, limit: number): any {
let lastFunc: ReturnType<typeof setTimeout> | 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
Expand Down
28 changes: 21 additions & 7 deletions panel/models/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof setTimeout> | 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))
}
}
}
Expand Down

0 comments on commit 89b0bc6

Please sign in to comment.