no-arbitrary-setTimeout.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @fileoverview Reject use of non-zero values in setTimeout
  3. *
  4. * This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7. */
  8. "use strict";
  9. var helpers = require("../helpers");
  10. var testTypes = new Set(["browser", "xpcshell"]);
  11. module.exports = {
  12. meta: {
  13. docs: {
  14. url:
  15. "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/no-arbitrary-setTimeout.html",
  16. },
  17. type: "problem",
  18. },
  19. create(context) {
  20. // We don't want to run this on mochitest plain as it already
  21. // prevents flaky setTimeout at runtime. This check is built-in
  22. // to the rule itself as sometimes other tests can live alongside
  23. // plain mochitests and so it can't be configured via eslintrc.
  24. if (!testTypes.has(helpers.getTestType(context))) {
  25. return {};
  26. }
  27. return {
  28. CallExpression(node) {
  29. let callee = node.callee;
  30. if (callee.type === "MemberExpression") {
  31. if (
  32. callee.property.name !== "setTimeout" ||
  33. callee.object.name !== "window" ||
  34. node.arguments.length < 2
  35. ) {
  36. return;
  37. }
  38. } else if (callee.type === "Identifier") {
  39. if (callee.name !== "setTimeout" || node.arguments.length < 2) {
  40. return;
  41. }
  42. } else {
  43. return;
  44. }
  45. let timeout = node.arguments[1];
  46. if (timeout.type !== "Literal" || timeout.value > 0) {
  47. context.report(
  48. node,
  49. "listen for events instead of setTimeout() " +
  50. "with arbitrary delay"
  51. );
  52. }
  53. },
  54. };
  55. },
  56. };