Chestnut:
stop the button being called
more than once within 1 second; first, the result of my baidu
btn.onclick = function add(){
btn.innerHTML = Number(btn.innerHTML) + 1;
btn.onclick = null;
clearTimeout(timer);
var timer = setTimeout(function(){
btn.onclick = add;
},1000);
}
btn.onclick = (function(){
var last = Date.now();
return function(){
var now = Date.now();
if((now - last)>1000){
btn.innerHTML= Number(btn.innerHTML) + 1;
}
last = now;
}
})();
both of the above methods can be implemented, and the question that puzzles me at present is:
1-is there a better way to use timers or closures;
2-if not, which of the above two methods is more suitable for component-based public use?
there are many places that need to be used in the current project, so I would like to try to encapsulate a simple public method myself, which can support click
events to prevent multiple calls within 1 second, or custom extensions (later).
the project is based on angular4.x (no similar method for deferring execution has been found.), of course, native js is completely OK
.