简体   繁体   中英

How to add setTimeout to document.body.addEventListener?

this is the javascript code I want to execute with 3 seconds delay. How will it looks like with setTimeout? Thanks in advance!

  <script type="text/javascript"> document.body.addEventListener('click', myFunction); function myFunction() { if (window.location.href.indexOf('3124') <= -1) { window.open('http://example.net/1_of_3/file_5444','mywindow2','width=1600,height=1200'); document.body.removeEventListener('click', myFunction); } } </script> 

Try this:

  <script type="text/javascript">
  document.body.addEventListener('click',function(){
   setTimeout(myFunction,3*1000);
 });
function myFunction() {
if (window.location.href.indexOf('3124') <= -1) {
window.open('http://example.net/1_of_3/file_5444','mywindow2','width=1600,height=1200');
        document.body.removeEventListener('click', myFunction);
    } 
}
    </script>

Maybe something along these lines?

 function myFunction() { document.querySelector('body').addEventListener('click', function(){ console.log('Do Stuff'); }); } setTimeout(myFunction, 3000); 
 .square { width: 100px; height: 100px; background-color: black; } 
 <body> <div class="square"></div> </body> 

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