0

I'm going to be executing lot's of setIntervals, there's a way to make it more efficient; but that's down the road.

Is there a way I can do this?

var a = setInterval(function(a){
    console.log(a);
    clearInterval(a);
}, 1000, a);

So the ID is parsed into the function itself, this way I wont have to store the ID to clear it again.

  • 2
    Perhaps you could use [setTimeout](http://stackoverflow.com/questions/13686867/setinterval-and-clearinterval-how-to-run-only-1-time) instead? – Frank Tan Aug 19 '16 at 20:52
  • Thanks for the suggestion, would work but I was just looking for a few quick changes to test, I'll end up making more efficient like i said to use only one set interval as a main loop rather than sub loops. –  Aug 19 '16 at 20:57

3 Answers3

2

You could write a helper function that does that:

function interval(f, timeout) {
  const id = setInterval(() => f(id), timeout);
}

interval(a => { console.log(a); clearInterval(a); }, 1000);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

You have two options here.

Recursive setTimeout:

function doTheJob() {
  console.log("I'm working")
  setTimeout(doTheJob, 1000)
}

Simple setinterval with leaving the variable(id) in scope:

var id = setInterval(function() {
  console.log("I'm working")

  if( something ) 
    clearInterval(id)   
}, 1000)
Lazyexpert
  • 3,106
  • 1
  • 19
  • 33
  • What exactly is the `.bind(this)` for? The lexical scope of a function is not affected by `.bind`. – Felix Kling Aug 19 '16 at 21:03
  • Just to be clear, your second solution works exactly the same without `.bind(this)`. `bind` sets the `this` value of the function. Since you are not using `this` inside the function it doesn't matter what the value is set to. Don't confuse `this` with scope. – Felix Kling Aug 19 '16 at 21:08
  • Thanks, already figured this out. I bet setTimeout and setInteval changed the scope before =) – Lazyexpert Aug 19 '16 at 21:10
  • If I do this several times though, the variable will be re-written, thus I'm using an object with the key being each players unique ID, although this isn't the best; I'll be upgrading to using a single loop eventually. Thanks for your suggestion of the tail chasing function! –  Aug 19 '16 at 22:11
0
var a = [];
a.push(setInterval(function(t){
    console.log(a[t]);
    clearInterval(a[t]);
}, 1000, a.length));

Don't do like that.

Aikon Mogwai
  • 4,954
  • 2
  • 18
  • 31
  • Interesting idea, although a bit messy! Thanks for your suggestion! –  Aug 19 '16 at 22:13