简体   繁体   中英

Checking time since last key was pressed

I'm making a script that requires the ability to redirect someone if a key has not been pressed within 15 seconds, the only problem is I don't know how to check how much time has lapsed since the last key was pressed.

I am aware of keyboard events but they wait for input instead of checking when last input was received.

This is rather simple implementation, but should offer you guidelines on how to build your own:

 let timeout; const handleKeyUp = (ev) => { clearTimeout(timeout); timeout = setTimeout(() => { location.href = '//google.com' }, 15e3); } window.addEventListener('keyup', handleKeyUp);

 let timeout; $(window).keypress(function(e) { if(timeout) { clearTimeout(timeout); timeout = null; } timeout = setTimeout(() => console.log(e.key), 1500) // 1.5 sec so you can see the effect quicker });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Try something like this:

HTML:

<input class="form-control" type="text" id="input">
<input type="hidden" value="0" id="lastKeyPressTime">

Javascript:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script>
    function inactivitiy(){
        var lastTime = $('#lastKeyPressTime').val();
        lastTime++;
        $('#lastKeyPressTime').val(lastTime);
        if(lastTime>15){
            //alert('time to redirect !');
            window.location = "http://www.example.com";
        }
        setTimeout(function(){
            inactivitiy();
        }, 1000);
    }
    $(document).ready(function(){
        $('#input').on('keypress', function(){
            $('#lastKeyPressTime').val(0);
        });

        inactivitiy();

    });
</script>

This should do the trick

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