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 🙂
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
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:
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.