def __init__(self, func, wait, max_wait=False): self.func = func self.wait = wait self.max_wait = max_wait self.last_result = None # Initialize last_* times to be prior to the wait periods so that func # is primed to be executed on first call. self.last_call = pyd.now() - self.wait self.last_execution = pyd.now() - max_wait if pyd.is_number( max_wait) else None
def __init__(self, func, wait, max_wait=False): self.func = func self.wait = wait self.max_wait = max_wait self.last_result = None # Initialize last_* times to be prior to the wait periods so that func # is primed to be executed on first call. self.last_call = pyd.now() - self.wait self.last_execution = (pyd.now() - max_wait if pyd.is_number(max_wait) else None)
def test_debounce_max_wait(): def func(): return _.now() wait = 250 max_wait = 300 debounced = _.debounce(func, wait, max_wait=max_wait) start = _.now() present = _.now() expected = debounced() while (present - start) <= (max_wait + 5): result = debounced() present = _.now() assert result > expected
def test_throttle(): def func(): return _.now() wait = 250 throttled = _.throttle(func, wait) start = _.now() present = _.now() expected = throttled() while (present - start) < (wait - 50): result = throttled() present = _.now() assert result == expected time.sleep(100 / 1000.0) assert throttled() > expected
def __call__(self, *args, **kargs): """Execute :attr:`func` if function hasn't been called witinin last :attr:`wait` milliseconds. Return results of last successful call. """ present = pyd.now() if (present - self.last_execution) >= self.wait: self.last_result = self.func(*args, **kargs) self.last_execution = present return self.last_result
def test_debounce(): def func(): return _.now() wait = 250 debounced = _.debounce(func, wait) start = _.now() present = _.now() expected = debounced() while (present - start) <= wait + 100: result = debounced() present = _.now() assert result == expected time.sleep(wait / 1000.0) result = debounced() assert result > expected
def func(): return _.now() wait = 250
def test_now(): present = int(time.time() * 1000) # Add some leeway when comparing time. assert (present - 1) <= _.now() <= (present + 1)
def __init__(self, func, wait): self.func = func self.wait = wait self.last_result = None self.last_execution = pyd.now() - self.wait
def func(): return _.now()