The right template for the best way to pass function parameters to setTimeout call in JavaScript

I try my best to pass all the parameters passed to the function to the function in setTimeout . That is, in my example below, I pass one parameter, but it seems to me that this is becoming more complex, it is becoming ugly (several parameters). I hope for a clean sample to do this because I do it a lot.

 onSessionTimeComboChange: function (combo, newValue, oldValue, eOpts) { var me = this; me.newValue = newValue; setTimeout(function () { var x = me.newValue; debugger; }, 100); } 
+4
source share
2 answers

The reason you don’t have access to the main variables of the function in the callback is because the code executed by setTimeout() is executed in a separate execution context for the function from which it was called. Simply put, this not the same in callback.

If you do not want to use the Javascript libraries that provide functions for binding the callback to the context (see jQuery.proxy and underscore.bind ), you will need to write your own non-native setTimeout function to fix this.

Here is the solution suggested in the web api docs (see The "this" problem section):

 window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2); return __nativeST__(vCallback instanceof Function ? function () { vCallback.apply(oThis, aArgs); } : vCallback, nDelay); }; 

If you don't want to go this far, improving your code would be to pass arguments to the callback as parameters to setTimeout :

 var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]); 

Read the JavaScript web api for more details.

So, in your example, you can simply write something like:

 setTimeout(function (x) { debugger; }, 100, newValue); 
+4
source

Javascript supports closure , so you can pass any parameters needed for any callback without much effort:

 function bar(x, y, z) { console.log([x, y, z]); } for (var i=0; i<5; i++) { (function(x, y, z){ setTimeout(function(){bar(x, y, z);}, i*1000+1000); })(i, i*2, i*3); } 

The only tricky part is that you cannot just say

 setTimeout(function(){bar(i, i*2, i*3)}, i*1000+1000); 

because the closure fixes the variables (and not the current values), so all registered functions actually use the same value of i in this case.

+4
source

Source: https://habr.com/ru/post/1500054/


All Articles