samedi 9 juillet 2016

How To Stop setTimeout() That Has Already Fired [on hold]


I am wondering how would I stop a setTimeout() that has already started? In my example below I have two buttons: .start and .cancel. Pressing .start would invoke the timer which will execute a console.log() after 2 seconds. I am trying to get the behavior where clicking .cancel would stop the timer from executing and to clear its queue. Is this possible? The issue I am experiencing is that if I click on .start, and then immediately click on .cancel before the 2 second, I will still see btn clicked in the console. I do not want to see that console message. var timer; $('.start').on('mousedown', function() { timer = setTimeout(function() { console.log('btn clicked'); }, 2000); }); $('.cancel').on('mousedown', function() { clearTimeout(timer); }); https://jsfiddle.net/xL8yquoL/

Aucun commentaire:

Enregistrer un commentaire