如何在keypress函数中使用setTimeout函数

时间:2017-11-22 07:57:56

标签: javascript jquery html settimeout onkeypress

我希望我的按键功能在每次按下都有效,但是setTimeout不能正常工作。这是我的html和脚本;

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>

脚本:

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);
}

1 个答案:

答案 0 :(得分:1)

您需要确定逻辑是什么。如果想法是在10秒后将对话框打开一次,那么你需要做这样的事情

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);
}

另一方面,如果您只想在完成输入后打开对话框

 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);
    }

注意10000毫秒约为10秒