Skip to content

Throttling and debouncing

When a function is called many times in quick succession (for example, by a slider's valueChanged signal while it's dragged), throttling and debouncing limit how often it actually runs:

  • Throttling runs it at most once per timeout. With the default (leading) policy, the first call runs at once, and further calls during the timeout are combined into one call at its end.
  • Debouncing waits until the calls have stopped for the timeout, and then runs it once.

Below, a slider's valueChanged signal is connected to a function directly, and to the same function decorated with qthrottled and with qdebounced. Each tick is a call, and the value is what the last call received:

Throttling and debouncing Throttling and debouncing
The code for this demo
"""A slider's valueChanged, connected directly, throttled, and debounced.

Drag the slider: each lane of the timeline draws a tick for each call (newest on
the right), and shows the value that the last call received. (Inspired by
examples/throttler_demo.py, which is adapted from KDAB's KDToolBox.)
"""

import time
from collections import deque

from qtpy.QtCore import QPointF, QRectF, QSize, Qt, QTimer
from qtpy.QtGui import QColor, QPainter, QPen
from qtpy.QtWidgets import QApplication, QSlider, QVBoxLayout, QWidget

from superqt.utils import qdebounced, qthrottled

SPEED = 100  # pixels per second
LABEL_WIDTH = 170


class Timeline(QWidget):
    """Lanes of ticks that scroll to the left, one lane per kind of call."""

    def __init__(self, lanes: dict[str, str]) -> None:
        super().__init__()
        self._colors = lanes  # lane name -> tick color
        self._ticks = {name: deque() for name in lanes}
        self._values = dict.fromkeys(lanes, "")
        self._timer = QTimer(self, interval=16, timeout=self.update)
        self._timer.start()

    def sizeHint(self) -> QSize:
        return QSize(480, 150)

    def add(self, lane: str, value: int) -> None:
        self._ticks[lane].append(time.perf_counter())
        self._values[lane] = str(value)

    def paintEvent(self, event) -> None:
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        palette = self.palette()
        painter.fillRect(self.rect(), palette.base())
        now, height = time.perf_counter(), self.height() / len(self._ticks)
        for i, (lane, ticks) in enumerate(self._ticks.items()):
            top = i * height
            # the lane's name, and the last value it received
            painter.setPen(palette.text().color())
            label = QRectF(10, top, LABEL_WIDTH - 20, height)
            align = Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
            painter.drawText(label, align, f"{lane}\n{self._values[lane]}")
            # a tick for each call
            painter.setPen(QPen(QColor(self._colors[lane]), 2))
            for t in ticks:
                x = self.width() - (now - t) * SPEED
                painter.drawLine(QPointF(x, top + 8), QPointF(x, top + height - 8))
            while ticks and self.width() - (now - ticks[0]) * SPEED < LABEL_WIDTH:
                ticks.popleft()


app = QApplication([])

window = QWidget()
slider = QSlider(Qt.Orientation.Horizontal)
slider.setValue(20)
timeline = Timeline(
    {
        "valueChanged": "#8c8c8c",
        "qthrottled (100 ms)": "#3b82f6",
        "qdebounced (300 ms)": "#f59e0b",
    }
)
layout = QVBoxLayout(window)
layout.addWidget(slider)
layout.addWidget(timeline)


@qthrottled(timeout=100)
def throttled(value: int) -> None:
    timeline.add("qthrottled (100 ms)", value)


@qdebounced(timeout=300)
def debounced(value: int) -> None:
    timeline.add("qdebounced (300 ms)", value)


slider.valueChanged.connect(lambda value: timeline.add("valueChanged", value))
slider.valueChanged.connect(throttled)
slider.valueChanged.connect(debounced)

window.show()
app.exec()

For more background, see Debouncing and throttling explained.

The qthrottled and qdebounced decorators wrap a function:

from superqt.utils import qdebounced, qthrottled


@qthrottled(timeout=100)  # milliseconds
def update_preview(value): ...


@qdebounced(timeout=300)
def save_settings(value): ...


slider.valueChanged.connect(update_preview)
slider.valueChanged.connect(save_settings)

The decorated function is called with the arguments of the last call that it combined. The QSignalThrottler and QSignalDebouncer objects do the same for signals: connect a signal to their throttle() slot, and their triggered signal is emitted at the throttled (or debounced) rate:

from superqt.utils import QSignalThrottler

throttler = QSignalThrottler()
throttler.setTimeout(100)
slider.valueChanged.connect(throttler.throttle)
throttler.triggered.connect(update_view)

qthrottled

qthrottled(
    func: Callable[P, R],
    timeout: int = 100,
    leading: bool = True,
    timer_type: TimerType = PreciseTimer,
    parent: QObject | None = None,
) -> ThrottledCallable[P, R]
qthrottled(
    func: None = ...,
    timeout: int = 100,
    leading: bool = True,
    timer_type: TimerType = PreciseTimer,
    parent: QObject | None = None,
) -> Callable[
    [Callable[P, R]], ThrottledCallable[P, R]
]
qthrottled(
    func: Callable[P, R] | None = None,
    timeout: int = 100,
    leading: bool = True,
    timer_type: TimerType = PreciseTimer,
    parent: QObject | None = None,
) -> (
    ThrottledCallable[P, R]
    | Callable[
        [Callable[P, R]], ThrottledCallable[P, R]
    ]
)

Creates a throttled function that invokes func at most once per timeout.

The throttled function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the throttled function. Subsequent calls to the throttled function return the result of the last func invocation.

This decorator may be used with or without parameters.

Parameters:

  • func (Callable, default: None ) –

    A function to throttle

  • timeout (int, default: 100 ) –

    Timeout in milliseconds to wait before allowing another call, by default 100

  • leading (bool, default: True ) –

    Whether to invoke the function on the leading edge of the wait timer, by default True

  • timer_type (TimerType, default: PreciseTimer ) –

    The timer type. by default Qt.TimerType.PreciseTimer One of: - Qt.PreciseTimer: Precise timers try to keep millisecond accuracy - Qt.CoarseTimer: Coarse timers try to keep accuracy within 5% of the desired interval - Qt.VeryCoarseTimer: Very coarse timers only keep full second accuracy

  • parent (QObject | None, default: None ) –

    Parent object for timer. If using qthrottled as function it may be useful for cleaning data

qdebounced

qdebounced(
    func: Callable[P, R],
    timeout: int = 100,
    leading: bool = False,
    timer_type: TimerType = PreciseTimer,
    parent: QObject | None = None,
) -> ThrottledCallable[P, R]
qdebounced(
    func: None = ...,
    timeout: int = 100,
    leading: bool = False,
    timer_type: TimerType = PreciseTimer,
    parent: QObject | None = None,
) -> Callable[
    [Callable[P, R]], ThrottledCallable[P, R]
]
qdebounced(
    func: Callable[P, R] | None = None,
    timeout: int = 100,
    leading: bool = False,
    timer_type: TimerType = PreciseTimer,
    parent: QObject | None = None,
) -> (
    ThrottledCallable[P, R]
    | Callable[
        [Callable[P, R]], ThrottledCallable[P, R]
    ]
)

Creates a debounced function that delays invoking func.

func will not be invoked until timeout ms have elapsed since the last time the debounced function was invoked.

The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Options indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation.

This decorator may be used with or without parameters.

Parameters:

  • func (Callable, default: None ) –

    A function to throttle

  • timeout (int, default: 100 ) –

    Timeout in milliseconds to wait before allowing another call, by default 100

  • leading (bool, default: False ) –

    Whether to invoke the function on the leading edge of the wait timer, by default False

  • timer_type (TimerType, default: PreciseTimer ) –

    The timer type. by default Qt.TimerType.PreciseTimer One of: - Qt.PreciseTimer: Precise timers try to keep millisecond accuracy - Qt.CoarseTimer: Coarse timers try to keep accuracy within 5% of the desired interval - Qt.VeryCoarseTimer: Very coarse timers only keep full second accuracy

  • parent (QObject | None, default: None ) –

    Parent object for timer. If using qthrottled as function it may be useful for cleaning data

QSignalThrottler

QSignalThrottler(
    policy: EmissionPolicy = Leading,
    parent: QObject | None = None,
)

A Signal Throttler.

This object's triggered signal will emit at most once per timeout (set with setTimeout()).

QSignalDebouncer

QSignalDebouncer(
    policy: EmissionPolicy = Trailing,
    parent: QObject | None = None,
)

A Signal Debouncer.

This object's triggered signal will not be emitted until self.timeout() milliseconds have elapsed since the last time triggered was emitted.

GenericSignalThrottler

GenericSignalThrottler(
    kind: Kind,
    emissionPolicy: EmissionPolicy,
    parent: QObject | None = None,
)

kind

kind() -> Kind

Return the kind of throttler (throttler or debouncer).

emissionPolicy

emissionPolicy() -> EmissionPolicy

Return the emission policy (trailing or leading).

timeout

timeout() -> int

Return current timeout in milliseconds.

setTimeout

setTimeout(timeout: int) -> None

Set timeout in milliseconds.

timerType

timerType() -> TimerType

Return current Qt.TimerType.

setTimerType

setTimerType(timerType: TimerType) -> None

Set current Qt.TimerType.

throttle

throttle() -> None

Emit triggered if not running, then start timer.

cancel

cancel() -> None

Cancel any pending emissions.

flush

flush(restart_timer: bool = True) -> None

Force emission of any pending emissions.

Parameters:

  • restart_timer (bool, default: True ) –

    Whether to restart the timer after flushing. Defaults to True.