简体   繁体   中英

Stop execution of function if user clicks on a div in Javascript or Jquery

When user loads a page, I trigger a "timer" that will show the message after 8 seconds. My problem is that I would like to prevent the message to be displayed in case the user clicks on the div #contentAfterIntro before those 8 seconds.

xoxo();
function xoxo(e) {
   setTimeout(showMessage, 8000);
   $("#contentAfterIntro").on('click', function(e) {
     e.stopPropagation();
   });
}

function showMessage() {   
    $('#msg').addClass('visible');
    console.log('show msg');
  }

The code above does not work. In my tests, even if I click before the 8 seconds, the messages gets displayed.

How to achieve this ?

setTimeout returns an id which you can use to cancel the timeout:

xoxo();
function xoxo(e) {
   var id = setTimeout(showMessage, 8000);
   $("#contentAfterIntro").on('click', function(e) {
     e.stopPropagation();
     clearTimeout(id); // <--- clear timeout
   });
}

function showMessage() {   
    $('#msg').addClass('visible');
    console.log('show msg');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM