After reading the throttling code implemented by others, I don't understand the meaning of this,arguments in this closure. Please give me some advice.

function throttle(fn,interval){
var timer,
    isFirst = true;
return function(){
//////////////////////////////////////////////////////////////////////
    var args = arguments,      
        that = this;
///////////////////////////////////////////////////////////////////////
    if(isFirst){
        fn.apply(that,args)
        return isFirst = false
    }
    if(timer){
        return
    }
    timer = setTimeout(() => {
        clearTimeout(timer)
        timer = null
        fn.apply(that,args)
    }, interval || 1000);
}   
}
Apr.02,2021

first of all, you have to understand that the function of throttle is to accept a function and return a new function, which has throttling function .

usage would look like this:

function handleClick(param) {console.log('clicked', param)};

const throttledHandleClick = throttle(handleClick, 2000)

// clicked
throttledHandleClick('p')
throttledHandleClick('p')
throttledHandleClick('p')

so what you mean by arguments is actually

.
{
 0 : 'p',
}
if you don't fn.apply (that,arguments), but fn (), then parameters will be lost

about this, this should depend on how the function is generated, throttle (handleClick, 2000) , so this is window. Rather than depending on how the final function throttledHandleClick is called, as you write.

if according to my understanding, it should be written like this:

function throttle(fn,interval){
    var timer,
        isFirst = true;
        that = this; // 
return function(){
    if(isFirst){
        fn.apply(that,arguments)
        return isFirst = false
    }
    timer = setTimeout(() => {
        clearTimeout(timer)
        timer = null
        fn.apply(that,arguments)
    }, interval || 1000);
}   
}

arguments is the parameter passed when the current function is called. This is a special built-in parameter, and the value of another method block is different, so use var args = arguments to copy a copy of the parameter when the current function is called.

var that = this is also a copy of the current context, or this pointing.

these two lines of code are a copy of the call in the following timer, which involves a series of knowledge points such as this pointing, scope, and so on.


this should be habitual writing.
in the case of this code, it does not involve the context change caused by the construction closure, and it will work without this step of referencing.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e560f6-442f9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e560f6-442f9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?