|
427 | 427 | "widgets.VBox([slider, text])"
|
428 | 428 | ]
|
429 | 429 | },
|
| 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 | + }, |
430 | 441 | {
|
431 | 442 | "cell_type": "code",
|
432 | 443 | "execution_count": null,
|
433 | 444 | "metadata": {},
|
434 | 445 | "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 | + ] |
436 | 480 | },
|
437 | 481 | {
|
438 | 482 | "cell_type": "markdown",
|
|
466 | 510 | "name": "python",
|
467 | 511 | "nbconvert_exporter": "python",
|
468 | 512 | "pygments_lexer": "ipython3",
|
469 |
| - "version": "3.7.3" |
| 513 | + "version": "3.8.1" |
470 | 514 | }
|
471 | 515 | },
|
472 | 516 | "nbformat": 4,
|
|
0 commit comments