Skip to content

Commit 3647dcb

Browse files
committed
Add throttling section
1 parent d6fab58 commit 3647dcb

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

docs/source/examples/Widget Events.ipynb

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -427,12 +427,56 @@
427427
"widgets.VBox([slider, text])"
428428
]
429429
},
430+
{
431+
"cell_type": "markdown",
432+
"metadata": {},
433+
"source": [
434+
"## Throttling\n",
435+
"\n",
436+
"Throttling is another technique that can be used to limit callbacks. Whereas debouncing ignores calls to a function if a certain amount of time has not passed since the last (attempt of) call to the function, throttling will just limit the rate of calls. This ensures that the function is regularly called.\n",
437+
"\n",
438+
"We show an synchronous solution below. Likewise, you can replace the `Timer` class with `from threading import Timer` if you want to use threads instead of asynchronous programming."
439+
]
440+
},
430441
{
431442
"cell_type": "code",
432443
"execution_count": null,
433444
"metadata": {},
434445
"outputs": [],
435-
"source": []
446+
"source": [
447+
"import asyncio\n",
448+
"from time import time\n",
449+
"\n",
450+
"def throttle(wait):\n",
451+
" \"\"\" Decorator that prevents a function from being called\n",
452+
" more than once every wait period. \"\"\"\n",
453+
" def decorator(fn):\n",
454+
" time_of_last_call = time()\n",
455+
" first_time = True\n",
456+
" def throttled(*args, **kwargs):\n",
457+
" def call_it():\n",
458+
" fn(*args, **kwargs)\n",
459+
" try:\n",
460+
" throttled.t.cancel()\n",
461+
" except(AttributeError):\n",
462+
" pass\n",
463+
" throttled.t = Timer(wait, call_it)\n",
464+
" nonlocal time_of_last_call, first_time\n",
465+
" now = time()\n",
466+
" if first_time or (now - time_of_last_call > wait):\n",
467+
" first_time = False\n",
468+
" time_of_last_call = now\n",
469+
" return fn(*args, **kwargs)\n",
470+
" return throttled\n",
471+
" return decorator"
472+
]
473+
},
474+
{
475+
"cell_type": "markdown",
476+
"metadata": {},
477+
"source": [
478+
"To see how different it behaves compared to the debouncer, you can decorate the `value_changed` function above with `throttle(0.2)` instead of `debounce(0.2)`. Note that both decorators should not be used together."
479+
]
436480
},
437481
{
438482
"cell_type": "markdown",
@@ -466,7 +510,7 @@
466510
"name": "python",
467511
"nbconvert_exporter": "python",
468512
"pygments_lexer": "ipython3",
469-
"version": "3.7.3"
513+
"version": "3.8.1"
470514
}
471515
},
472516
"nbformat": 4,

0 commit comments

Comments
 (0)