There is a function to be started by clicking, "console.log ()".

The only nuance is that the function is launched at the first click, with the next clicks for 2 seconds, the function should not start, and after 2 seconds at the click, the function starts again.

  • one
    flag and timeout. - Grundy

3 answers 3

Solution to the forehead: check the flag when clicked, if set, go out, if the timeout is run

For example:

var allowclick = true; function onclick(){ if(!allowClick) return; allowClick = false; //do function console.log(...) setTimeout(function(){allowClick = true; },2000) } 

    Well, I

     $(function() { var flag = true; $('a').on('click', function(event) { event.preventDefault(); if (flag) { console.log('flag=' + flag); $('#res').text($('#res').text() + ' flag=' + flag) flag = false; setTimeout(function() { flag = true; }, 2000); } }); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a href="#">Link</a> <div id="res"></div> 

      html

       <input type="button" id="test" value="123213"> 

      javascript

       var timeout; var clearInterval = true; $(document).on('click', '#test', function(e){ e.preventDefault(); if (clearInterval) { clearInterval = false; console.log('test phrase'); timeout = setTimeout(function() { clearTimeout(timeout); clearInterval = true; }, 2000); return false; } }); 

      Upd:

      As they say in the commentary: by the way, it makes no sense to do clearTimeout inside the handler, this is not an interval, it will be cleaned itself, a one-time fact. It would make sense to clear - outside to interrupt the timer.

      I left it just in case, but you can play around to see if you need it or not.

      • Something you somehow screwed up. it seems to me :) - Grundy
      • ..... ¯ \ _ (ツ) _ / ¯ ..... it is necessary to clear the interval ... plus the flag to reset ... - Alexey Shimansky
      • one
        By the way, it makes no sense to do clearTimeout inside the handler, this is not an interval, it will be cleared, because it is one-time. It would make sense to clear - outside to interrupt the timer - Grundy