How does this delay function work?

I use this code to wrap pieces of code in it like this,

var delay = (function() {
    // SET TIMER
    var timer = 0;
    // RETURN SET TIMEOUT FUNCTION
    return function(callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();​

I call it this:

delay(function() {
     .......
}, 1000);

And that will delay it for 1000 milliseconds, but I don’t understand what is happening thanks :)

+5
source share
3 answers

Delay is a function that will return another function. The timer variables are inside the closure of the delay function, so it can still be turned on by the return function. Function. You can also write this as

var delay;
var timer = 0;
delay = function(callback, ms) {
    clearTimeOut(timer);
    timer = setTimeout(callback, ms);
}

The problem you are currently facing is that if you cause a delay twice, it will overwrite the timer variables so that the second delay will overwrite the timer variable. I checked this, and it seems that your function is also violated, it should be:

var delay = function(){
// SET TIMER
    var timer = 0;
// RETURN SET TIMEOUT FUNCTION
    return function(callback, ms){
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
};

delay()(function(){console.log("hello1");}, 5000);
delay()(function(){console.log("hello2");}, 5000);

, hello2, .

, , .

+6

, , - ( () , ):

function() {
    // SET TIMER
    var timer = 0;
    // RETURN SET TIMEOUT FUNCTION
    return function(callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
}​

delay. timer, . :

function(callback, ms) {
   clearTimeout(timer);
   timer = setTimeout(callback, ms);
}

, timer. timer. , timer.

: delay (function(callback, ms) {...), timer. timer . , delay.

, delay(callback, timeout).

+2

u , , , .., ,

return function(callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    }

var varible. - , u , ..

delay(function() {
     .......
}, 1000);

this wud works as expected.
also pay attention to ()the end where u indicates the variable delay.. which in javascript means the function starts as soon as it occurs .. therefore, when the first part of the code that I saw is launched and the delayfunction is assigned to the variable. which you call in the second part of the code

0
source

All Articles