简体   繁体   中英

How to work once setTimeout function that in keypress function

I want to my keypress fuction works every press but setTimeout dosen't work. here is my html and scripts;

html:

    <div  id="fake" class="full-height col-md-3 col-sm-12 col-xs-12">
        <div class="nav-right">
            <div class="form-search">
                <input  id="fake-search" onkeypress="dialogTrigger(event)" class="fake-search" type="text" />
            </div>
        </div>
    </div>

scripts:

function dialogTrigger(event) {
    var keyboardInput = event.which;
    keyboardInput = keyboardInput + 5;
    var changedInput = String.fromCharCode(keyboardInput);
    $("#fake-search").val($("#fake-search").val() + changedInput);
    setTimeout(function () {
       doSomething(); // about html
    }, 10000);
}

You need to decide what the logic is. If the idea is to throttle a dialog open once after 10 seconds then you would need to do something like this

var to;
function dialogTrigger(event) {
    var keyboardInput = event.which;
    keyboardInput = keyboardInput + 5;
    var changedInput = String.fromCharCode(keyboardInput);
    $("#fake-search").val($("#fake-search").val() + changedInput);

    // The line below will only start the timer if none exists;

    to = to || setTimeout(function () {
       doSomething(); // about html
    }, 10000);
}

On the other hand if you want to only open the dialog after they finish typing

 var to;
    function dialogTrigger(event) {
        var keyboardInput = event.which;
        keyboardInput = keyboardInput + 5;
        var changedInput = String.fromCharCode(keyboardInput);
        $("#fake-search").val($("#fake-search").val() + changedInput);

        // The line below clear any existing timeout and start a new one

        if (to) clearTimeout(to);
        to =  setTimeout(function () {
           doSomething(); // about html
        }, 10000);
    }

Note 10000ms is about 10 seconds

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