1

Execute function only one time in Javascript, no matter how many times it has been called. I write the following code, but does not working.

var counter = 0;

if(n.data === YT.PlayerState.BUFFERING) {
  setTimeout(function() {                 
    if(counter===0) {
      r.frontPlayer.seekTo(10);
      counter++;
  }}, 2000);
}                 
4
  • 3
    For that specific function, you don't even need the counter. setTimeout will only run it once. If you're running this whole block of code multiple times, then that's a different problem. Commented May 11, 2016 at 21:39
  • 2
    It looks like var counter = 0; is in the same scope where setTimeout is declared Commented May 11, 2016 at 21:40
  • which function are you talking about? setTimeout callback function or r.frontPlayer.seekTo(10) ? setTimeout callback function will run only once unless the whole code block you wrote executes again. Commented May 11, 2016 at 21:43
  • if(n.data === YT.PlayerState.BUFFERING) { r.frontPlayer.seekTo(10); } Commented May 11, 2016 at 21:44

2 Answers 2

3

Try not to use timeouts, they invite misery and suffering. This is a simple example, I use jquery for attaching the events but the function is independent of jquery. The key thing is using the object, the anonymous function in this case, to track state.

<button id="testButton">
test
</button>

$("#testButton").click(function() {
    if (null == this.ran) {
    console.log("do something");
    this.ran = true;
  }
})
Sign up to request clarification or add additional context in comments.

Comments

1

Take a look at underscore or lodash's _.once function:

var fn = _.once(function() {
  console.log('this will only run once');
});

Or writing it yourself:

var fn = (function() {
  var called = false;
  var ret;

  return function() {
    if (called) return ret;
    called = true;
    // do stuff
    // .. 
    ret = 'some return value';
    return ret;
  };
})();

2 Comments

Really? You want him to use a library just for this...?
@Mikey Accidentally pressed submit before posting a "polyfill"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.