Skip to content

Async tests w/ setTimeout, Date.now() fail #1845

Closed
@luwes

Description

@luwes

Description

Pretty simple tests for a throttle and debounce function are failing in async tests. If these are put in the test.serial they do pass.

Test Source

test('more throttling', async t => {
  let counter = 0;
  const incr = () => counter++;
  const throttledIncr = l.throttle(30, incr);

  throttledIncr();
  throttledIncr();
  t.is(counter, 1);
  await delay(85);

  t.is(counter, 2);
  throttledIncr();
  t.is(counter, 3);
});
/**
 * Throttle a function.
 *
 * @func
 * @since v0.2.0
 * @category Function
 * @param  {Number}   wait
 * @param  {Function} fn
 * @param  {Object}   [options]
 * @param  {Boolean}  [options.leading=true] - Trigger a leading function call.
 * @param  {Boolean}  [options.trailing=true] - Trigger a trailing function call.
 * @return {Function}
 */
export default function throttle(wait, fn, options = {}) {
  let timeout, context, args, result;
  let previous = 0;

  const later = function() {
    previous = options.leading === false ? 0 : Date.now();
    timeout = null;
    result = fn.apply(context, args);
    if (!timeout) context = args = null;
  };

  const throttled = function() {
    const now = Date.now();
    if (!previous && options.leading === false) previous = now;
    const remaining = wait - (now - previous);
    context = this;
    args = arguments;
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      previous = now;
      result = fn.apply(context, args);
      if (!timeout) context = args = null;
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }
    return result;
  };

  throttled.cancel = function() {
    clearTimeout(timeout);
    previous = 0;
    timeout = context = args = null;
  };

  return throttled;
}

Error Message & Stack Trace

screen shot 2018-06-18 at 11 49 16 pm

Config

Copy the relevant section from package.json:

{
  "ava": {
    "files": [
      "test/*.js"
    ],
    "sources": [
      "src/*.js"
    ],
    "require": [
      "esm",
      "@babel/register"
    ]
  }
}

Command-Line Arguments

ava

Relevant Links

Environment

Node.js v9.11.1
ava 1.0.0-beta.6
npm 5.6.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions