Kill, abort, stop, cancel a previous call/queue to a javascript function -
i have function take time run on click
event. following merely example , settimeout
there simulate time may take run it. how can ensure when user click on item previous running function(s) is(are) cancelled , latest onclick
function fired?
i.e. if user clicked on 10 times. want execute 10th click not 9 clicks before.
i hoping pure/vanilla js solution... not jquery
(function () { var nav = document.queryselector('.nav__toggle'); var togglestate = function (elem, one, two) { var elem = document.queryselector(elem); elem.setattribute('data-state', elem.getattribute('data-state') === 1 ? 2 : one); }; nav.onclick = function (e) { settimeout(function(){ togglestate('.nav ul', 'closed', 'open'); }, 5000); e.preventdefault(); }; })();
fiddle: http://jsfiddle.net/6p94p48m/
you need debounce click handler.
var button = document.getelementbyid("debounced"); var clickhandler = function() { alert('click handler'); } var debounce = function(f, debouncetimeout) { var to; return function() { cleartimeout(to); = settimeout(f, debouncetimeout); } } button.addeventlistener('click', debounce(clickhandler, 5000));
<button id="debounced" href="#">debounced</button>
or use underscore/lodash https://lodash.com/docs#debounce
Comments
Post a Comment