How does this "delay" function works

javascript

Solution

The delay is a function that will return another function. The timer variables is inside the closure of the delay function so it can still be accesed by the returning function. The function. You could also write it like this

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

The problem that you have now is that if you call delay twice it will overwrite the timer variables so the second delay will overwrite the timer variable. I tested this out and it seems that your function is also broken 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);

If your code does the same it will only trace hello2 because the first one will overwrite the timer variable.

Unless your intention is that a second delay will stop the first delay you should use a different approuch.

Problem

I am using this code to wrap parts of code in it is used 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 like this, ``` delay(function() { ....... }, 1000); ``` And it will delay it by 1000 milliseconds, but I do not understand what is going on thanks :)

Original source

Related problems