You need to write a function that counts pressing a certain button (in my case, a space) for a limited time. If the user has pressed the button the required number of times, the function should immediately return 1 (and not wait until the time is up), if the time is out then 0. My own code does not wait 10 seconds, but immediately displays "fail"; in addition, after quitting the qte function, it continues to respond to pressing the space bar.
var count = 0; var flag; function qte() { console.log('start'); var timerId = setTimeout(failed, 1000); $(document).keydown(function(key) { if (parseInt(key.which) === 32) { count++; console.log(count); if (count === 10) { clearTimeout(timerId); count = 0; flag = true; return; } } }); console.log(flag); if (flag !== undefined) return; } function failed() { flag = false; return; } $(document).ready(function() { $('div').click(function() { qte(); if (flag) console.log('success'); if (flag === false) console.log('fail'); return; }); }); div { height: 100px; width: 100px; border-radius: 100%; background-color: #ABCDEF; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div></div> </body>
$(document).keydown(function(key) {each time handler hangs up - Grundy