Passing a pointer/reference to a variable as parameter

后端 未结 5 1755
情话喂你
情话喂你 2021-01-24 17:40

I know this question has been asked multiple times (yes, I did some research) but I can\'t see to find a solution that fits my needs.

What I have done so far:

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-24 18:20

    How can this be accomplished?

    Not with a variable. There are no "references to variables" in JS. I can see two simple solutions:

    1. pass a getter/setter function:

      function queue(getStatus) {
          …
          getStatus() // gets current value
          …
      }
      
      var executed = false;
      queue(function() { return executed; });
      
    2. pass an object with a property:

      function queue(status) {
           …
          status.executed // gets current value
          …
      }
      
      var status = {executed: false};
      queue(status);
      

    I have come up with a solution that involves executing a function only once per {whatever} milliseconds. This involves a variable set to true or false, if the function has already been executed in the {whatever} milliseconds.

    I cannot see the reason why this variable would need to be a parameter to the function, and be available (or even settable?) outside it. Just use a local variable inside queue.

    Btw, this functionality is known as debouncing, you don't have to write this yourself. Many implementations are already available on the web, sometimes as part of larger libraries. See for example What does _.debounce do?.

提交回复
热议问题