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);
}                 
Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47
busterscruggz
  • 67
  • 2
  • 10
  • 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. – Mike Cluck May 11 '16 at 21:39
  • 2
    It looks like `var counter = 0;` is in the same scope where `setTimeout` is declared – Washington Guedes May 11 '16 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. – Saad May 11 '16 at 21:43
  • if(n.data === YT.PlayerState.BUFFERING) { r.frontPlayer.seekTo(10); } – busterscruggz May 11 '16 at 21:44

2 Answers2

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;
  }
})
Blue
  • 463
  • 4
  • 18
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;
  };
})();
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123