var delay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); - Read the help: What to do with the answers to my question - Bharata
3 answers
Since here before me there were quite detailed explanations in 2 answers, I will write a little differently: it makes the understanding of the code much easier if it is recorded in expanded form .
Your function and its call of the form delay(function(){console.log('test')}, 50); will fully comply with the following expanded view:
var delay = function() { /* переменная timer связана с областью видимости переменных. В данном случае она не засоряет глобальную область видимости, но при этом видима для функции funcTimeout. Читайте подробней про «Замыкания и область видимости» тут: https://learn.javascript.ru/functions-closures Про область видимости переменных тут: https://msdn.microsoft.com/ru-ru/library/bzt2dkta(v=vs.94).aspx */ var timer = 0; function funcTimeout(callback, ms) { clearTimeout (timer); timer = setTimeout(callback, ms); } //возвращает ссылку на функцию (но на этом месте //вместо неё можно писать саму функцию без имени) return funcTimeout } //Срока кода ниже делает следующее: //сначала получает ссылку на функцию, а затем //вызывает функцию с передачей входных значений. delay()(function(){console.log('test')}, 50); A little easier the last line of code can be written like this:
//получаем ссылку на функцию: var delayInnerFunction = delay(); //затем вызываем функцию delayInnerFunction(function(){console.log('test')}, 50); I hope you can now understand this feature. And they are recorded so briefly in order to transmit less code, because transferring code from the server to the client is an additional expense on both the client and the server.
- The server will not burn if it passes the function it has)) The readability of the code is no less important than its performance. - alvoro
This is an example of a closure . A very important part of the javascript language. The following example does the following:
- Assigns a
delayvariable to an anonymous function (declared on line 3), which has access to the local scope of the anonymous function declared on line 1, namely the variabletimer. The fact that the anonymous function declared on line 1 is "surrounded by parentheses" makes it called on the spot. - When calling the
delayfunction (essentially an anonymous function declared on line 3), the previously startedtimeris canceled and a new one is started (the link to it is stored in the local scope of the anonymous function declared on line 1 (in thetimervariable) and we have access to it only by calling an anonymous function stored in the variable 'delay').
Now, calling the function stored in the variable delay , we have to pass to it the callback function and the time in milliseconds when this (callback) function should be called.
The variable delay assigned the result of executing an immediately called function — namely, a function with a timer. inside this function timer used to save the timer id , if you call it several times then if the previous time this function has not yet been executed (the timer did not work) then the timer is reset and the countdown starts on a new one. I can not understand. I enclose an example of the function.
var delay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); delay(function(){console.log('test1')},100); delay(function(){console.log('test2')},100); delay(function(){console.log('test3')},100); delay(function(){console.log('test4')},100);