EricC
EricC

Reputation: 5870

How to call an anonymous function from setTimeout

I have a loop, a setTimout and a callback. I need to use an anonymous function to keep the variables correct in the callback.

I want to have the callback as a separate function because it is too large to have in the loop.

This does not work:

for (var i = 0; i < 10; i++) {
  setTimeout(callback, 1000*i, i);
}

var callback;
(callback = function(i) {
  console.log(i);
})();

How can define an anonymous function that I can call from setTimeout?

Upvotes: 0

Views: 103

Answers (5)

Adam Jenkins
Adam Jenkins

Reputation: 55613

I'm missing something, you're question is how to call an anonymous function, yet every single answer (including your own question) has included named functions.

What's wrong with:

for (var i = 0; i < 10; i++) {
  setTimeout(function(m) { console.log(m); }, 1000*i, i);
}

Upvotes: 0

Tom O.
Tom O.

Reputation: 5941

If I understand correctly, it would seem to me that it's more logical to use setInterval() than setTimeout() in conjunction with a for-loop.

I've created a callback function using a closure to keep track of the counter variable in my example:

function init() {
  var increment = initCounter();

  setInterval(function() {
    console.log(increment());
  }, 1000);
}


function initCounter() {
  var i = 0;
  return function() {
    return ++i;
  }
}

init();

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272477

It appears that you don't need anything more complex than this:

function callback(i) {
  console.log(i);
};

for (var i = 0; i < 10; i++) {
  setTimeout(callback, 1000*i, i);
}

You had two issues:

  • You tried to use callback before you'd defined it.
  • You wrapped your function in an IIFE (for no apparent reason), which means it would have been invoked once with an undefined argument.

Upvotes: 1

Jimmy Leahy
Jimmy Leahy

Reputation: 666

Using ES6 Arrow Functions:

let callback = (i) => {
  console.log(i);
}

for (var i = 0; i < 10; i++) {
  setTimeout(callback, 1000, i);
}

Upvotes: 1

Ele
Ele

Reputation: 33726

Just put the for-loop after the function expression.

This is following your approach.

var callback;
(callback = function(i) {
  if (i !== undefined)
    console.log(i);
})();

for (var i = 0; i < 10; i++) {
  setTimeout(callback, 1000, i);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

Better approach using function declaration:

function callback(i) {
    console.log(i);
};

for (var i = 0; i < 10; i++) {
  setTimeout(callback, 1000, i);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions