Home > Web Front-end > JS Tutorial > How to execute the keydown event at intervals in jquery?

How to execute the keydown event at intervals in jquery?

黄舟
Release: 2017-06-27 13:47:40
Original
2056 people have browsed it

If you use keydownevent, then if you hold it down, it will continue to execute. Now I need to implement it only once even if I hold it down.

Can I set the execution interval of keydown? Can it be executed every 400ms while holding down a certain key?

$(document).keydown(function(e){   //按下去就执行,按照事件类型来进行分类

var  corelist = $('.corelist_item');
var  readfloor = $('.J_read_floor');
if(corelist.length || readfloor.length){
if(e.keyCode == 87){    // w键 上一篇/楼
listJump(false,10,corelist);
listJump(false,55,readfloor);
}

});
Copy after login

Write code/I also want to play the piano/The front end is just a Title/Collect resume

keydown and keyup are a pair.
So if you monitor the keyup, you can exclude the keydown that is triggered when the key is held down.
For example, set a bool=true, bool=true during keyup; judge whether bool is true during keydown, execute it only if true, and then bool=false.

If the page allows it,
In addition to judging by parameters, you can also use jQuery's one(), which will only be executed once

$(btn).one("keydown",function(){
//dosomething
});
Copy after login

Use jQuery's one() is only executed once when the page is not refreshed, but adding parameters is different. There is only one event when pressing and holding the keydown, but the keydown event is still bound when the keydown is released and pressed again.

Here’s a recipe you can try... It’s ugly and inaccurate, but JavaScript It’s impossible to achieve such accuracy in time.

(function() {
	var lock;
	var interval = 400;
	$(document).keydown(function() {
		var date = new Date();
		var time = date.getTime();
		if (typeof lock == 'undefined') {
			lock = time % interval;
		}
		if (Math.abs(lock - time % interval) < 13) {
			console.log(date.getHours() + &#39;:&#39; + date.getMinutes() + &#39;:&#39; + date.getSeconds() + &#39;:&#39; + date.getMilliseconds());
			//your code goes here!
		}
	}).keyup(function() {
		lock = undefined;
	});})();
Copy after login

The above is the detailed content of How to execute the keydown event at intervals in jquery?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template