[英]Javascript: How do I update my Event Listener to only make a change when the user STOPS typing?
I have this event listener: 我有这个事件监听器:
input_1.addEventListener('input',function(){
updateFromInput(1);
},false);
It controls the location of a slider. 它控制滑块的位置。
Right now, if I want to type "100" into the input, the slider will start by jumping to the "1" position, then jump to "10", then finally jump to the "100" position. 现在,如果我想在输入中键入“100”,滑块将从跳转到“1”位置开始,然后跳到“10”,最后跳到“100”位置。
It's pretty clunky, and I'd like to give it a more natural feel. 它非常笨重,我想给它一个更自然的感觉。
While I'm now pretty comfortable reading JS, I'm still quite the novice in writing it. 虽然我现在读JS很舒服,但我仍然是编写它的新手。
I understand the logic needed for this type of timer (if timer is greater than 750ms updateFromInput ), I'm just a bit hazy how to start coding that in javascript. 我理解这种类型的计时器所需的逻辑(如果计时器大于750ms updateFromInput ),我只是有点朦胧如何在javascript中开始编码。
Certainly this type of timer functionality has been done a million and one times before by just as many developers ... just struggling to find an example or two :) 当然这种类型的计时器功能已经完成了一百万次,只有很多开发人员......只是努力寻找一两个例子:)
Any code, links, or examples would be greatly appreciated. 任何代码,链接或示例将不胜感激。
The usual way would be to set a timer, and if you see another keystroke, cancel the previous timer and set a new one, eg: 通常的方法是设置一个计时器,如果你看到另一个击键,取消前一个计时器并设置一个新计时器,例如:
var timer = 0;
input_1.addEventListener('input',function(){
maybeUpdateFromInput(1);
},false);
function maybeUpdateFromInput(val) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
updateFromInput(val);
timer = 0;
}, 50); // 50 = 50ms, you may want 75, 100, even 125
}
That will delay the update by 50ms (the value on the setTimeout
call). 这将使更新延迟50ms(
setTimeout
调用的值)。 If it doesn't see input for more than 50ms, it will then update. 如果输入超过50毫秒,则会更新。
I think the better way to handle this is both on key down and on key up. 我认为处理这个问题的更好方法是关键时刻和关键时刻。 That way, in case the user presses and holds the key, it won't be misinterpreted.
这样,如果用户按下并按住键,则不会被误解。 Take a look at this jsFiddle:
看看这个jsFiddle:
http://jsfiddle.net/9c46B/3/ http://jsfiddle.net/9c46B/3/
Obviously, you'd have to change it to be adding event listeners (instead of inline handlers in the HTML). 显然,您必须将其更改为添加事件侦听器(而不是HTML中的内联处理程序)。 And obviously you'd change the alert to be whatever you want.
很明显,你会将警报改为你想要的任何东西。 But hopefully this helps and is what you're looking for!
但希望这有助于您正在寻找的东西!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.