用户停止输入后运行函数 [英] Run function after user has stopped typing

查看:22
本文介绍了用户停止输入后运行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段,用户可以在其中输入一个长值.然后将该值用作复杂耗时函数中的输入值.

I have an input field in which user can input a long value. This value is then used as input value in a complex time consuming function.

我的问题是:如何在用户完成输入大约 1 秒后开始执行此功能?(我不想在每次按键后运行它,因为它真的会减慢页面速度).因此,如果他的下一次击键距离上一次击键的时间在 1 秒以内,那么请再等待一秒.

My question is: how can I start execution of this function approximately 1 second after the user finished his typing? (I don't want to run it after each key press as it is really slowing the page). So if his next keystroke is in the 1s limit from the last key stroke, than wait additional second.

您有什么建议吗?

附加说明:我还需要向这个函数传递一些参数

additional note: I also need to pass some parameters into this function

推荐答案

这是一个草稿:http://jsfiddle.net/jomanlk/msmJp/

使用 setTimeoutclearTimeout

var timer = null;
    $('#text').keyup(function(){
           clearTimeout(timer); 
           timer = setTimeout(doStuff, 1000)
    });
    
    function doStuff() {
        alert('do stuff');
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='text'>

这篇关于用户停止输入后运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆