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(){
var timer = 0;
return function(callback, ms){
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
};
delay()(function(){console.log("hello1");}, 5000);
delay()(function(){console.log("hello2");}, 5000);
, hello2, .
, , .