actions/TimingActions.js

  1. /**
  2. * TimingActions - Actions related to time
  3. *
  4. * This code is licensed under the MIT License (MIT).
  5. *
  6. * Copyright 2020, 2021, 2022 Rolf Bagge, Janus B. Kristensen, CAVI,
  7. * Center for Advanced Visualization and Interaction, Aarhus University
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the “Software”), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. /**
  29. * Actions that deal with time
  30. * @namespace TimingActions
  31. */
  32. /**
  33. * An action "wait" that waits for a given duration before continuing
  34. * @memberOf TimingActions
  35. * @example
  36. * //Wait for 100ms
  37. * {
  38. * "wait": {
  39. * "duration": 100
  40. * }
  41. * }
  42. *
  43. * //Wait for 100ms (shorthand version)
  44. * {
  45. * "wait": 100
  46. * }
  47. */
  48. class WaitAction extends Action {
  49. static options() {
  50. return {
  51. "duration": "number"
  52. }
  53. }
  54. constructor(name, options, concept) {
  55. //shorthand
  56. if(typeof options === "number") {
  57. options = {
  58. "duration": options
  59. }
  60. }
  61. super(name, options, concept);
  62. }
  63. async apply(contexts, actionArguments) {
  64. if(this.options.duration == null) {
  65. throw new Error("Option 'duration' must be present on 'wait' action");
  66. }
  67. return this.forEachContext(contexts, actionArguments, async (context, options)=>{
  68. await new Promise((resolve)=>{
  69. setTimeout(()=>{
  70. resolve();
  71. }, options.duration);
  72. })
  73. return context;
  74. });
  75. }
  76. }
  77. Action.registerPrimitiveAction("wait", WaitAction);
  78. window.WaitAction = WaitAction;