用户停止输入时的Javascript操作

时间:2014-01-08 01:03:10

标签: javascript

我有以下代码:

<input name="qty" id="qty" type="text" value="value"/>

<script>
var timer = null;
$('#qty').keydown(function(){
   clearTimeout(timer); 
param = Math.round(Math.random() * 100);
timer = setTimeout(function(){
    alert('a param : ' + param);        
}, 1000)
});
</script>

这应该在用户停止输入时创建并发出警报。这里有一个工作演示:http://jsfiddle.net/jomanlk/msmJp/1/

然而,我似乎无法让它在我的最终工作。

1 个答案:

答案 0 :(得分:1)

虽然OP发现他的回答只是忘记了包含jQuery,但我想我会抓住这个机会向你抛出所有可以使这样的事情更易于处理的片段。 (并不是说它真的很难

以下内容使typing stopped -> do action问题与单个方法调用一样简单。

/** debounce(callback, arguments, delay, object)
 *  Method to help reduce multifire issues 
 **/
;(function() {
function debounce(cb, args, delay, obj) {
    void 0 == obj && (obj = window);
    obj['__debounce_timer__'] && clearTimeout(obj['__debounce_timer__']);
    args = 'object' == typeof args ? Array.prototype.slice.call(args) : void 0 != args ? [args] : arguments;
    (0 > delay || "number" != typeof delay) && (delay = 250);   //  250 milliseconds as a default delay time
    return obj['__debounce_timer__'] = setTimeout(function() { delete obj['__debounce_timer__']; cb.apply(obj, args); }, delay);
}
window.hasOwnProperty("debounce") || (window.debounce = debounce);
})();

使用OP的例子:

$('#qty').keydown(function(e){
    debounce(
        function() {
            param = Math.round(Math.random() * 100);
            alert('a param : ' + param);    
        },
        arguments,  //  in this case [e]
        1000,   //  time in milliseconds || default 250 milliseconds
        this    //  or simply void 0 || undefined || {}
    );
});

只是为了好玩,这是一个扩展版本。 ¡小心! 以下版本将debounce添加到Function对象。

/** debounce(callback, arguments, delay, object)    ||  Function.debounce(arguments, delay, object)
 *  Method to help reduce multifire issues 
 **/
;(function() {
    function debounce(cb, args, delay, obj) {
        void 0 == obj && (obj = window);
        obj['__debounce_timer__'] && clearTimeout(obj['__debounce_timer__']);
        args = 'object' == typeof args ? Array.prototype.slice.call(args) : void 0 != args ? [args] : arguments;
        (0 > delay || "number" != typeof delay) && (delay = 250);   //  250 milliseconds as a default delay time
        return obj['__debounce_timer__'] = setTimeout(function() { delete obj['__debounce_timer__']; cb.apply(obj, args); }, delay);
    }
    window.hasOwnProperty("debounce") || (window.debounce = debounce);
    /** CAUTION APPENDS TO FUNCTION OBJECT **/
    function funcDebounce(args, delay, obj) { return debounce(this, args, delay, obj); }
    if (window.debounce === debounce) {
        Object['defineProperty'] && !Function.prototype.hasOwnProperty('funcDebounce')
            ? Object.defineProperty(Function.prototype, 'debounce', { value: funcDebounce })
                : Function.prototype.debounce = funcDebounce;
    }
})();

使用OP的例子:

function opCallBack() {
    param = Math.round(Math.random() * 100);
    alert('a param : ' + param);
}

$('#qty').keydown(function(e){
    opCallBack.debounce(arguments, 1000, this);
});

运行示例

function callBack() { $('#jon').removeClass('typeing').text('FINISHED TYPEING'); }
$('#bob').on('keyup', function(e) {
	$('#jon').addClass('typeing').text('typeing ...');
	debounce(callBack);
});
html, body, table { height: 100%; margin: 0 auto; text-align: center; vertical-align: middle; }
textarea { height: 8em; width: 16em; }
.typeing { background-color: #FCC; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/debounce/1be19005/debounce.min.js"></script>

<table>
	<tr>
		<td>
			<textarea id="bob" type="text" placeholder="Type Here"></textarea>
			<br />
			<div id="jon"></div>
		</td>
	</tr>
</table>