简体   繁体   中英

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?

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.

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(); 

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; } 

Using ES6 Arrow Functions :

 let callback = (i) => { console.log(i); } for (var i = 0; i < 10; i++) { setTimeout(callback, 1000, i); } 

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM