Javascript setTimeout not working | onkeydown - javascript

what I'm trying to do is when you hold w or s it should call function every second. But right now it only delays first call then it makes like 12 calls every second. Thanks in advance for anybody who will answer. I you want mor infos just ask.
<!DOCTYPE html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function call(direction) {
$.ajax({ url: '/' + direction });
}
</script>
<script>
document.onkeydown = function (event) {
var key_press = String.fromCharCode(event.keyCode);
var key_code = event.keyCode;
if (key_press == "W") {
direction = 'down';
} else if (key_press == "S") {
direction = 'up';
}
var update = setTimeout(function () {
call(direction)
}, 250);
}
document.onkeyup = function (event) {
clearTimeout(update);
}
</script>

Use setInterval instead of setTimeout. Also consider update as global var.
var update = '';
document.onkeydown = function (event) {
var key_press = String.fromCharCode(event.keyCode);
var key_code = event.keyCode;
if (key_press == "W") {
direction = 'down';
} else if (key_press == "S") {
direction = 'up';
}
if (!update) {
update = setInterval(function () {
call(direction)
}, 1000);
}
}
document.onkeyup = function (event) {
clearInterval(update);
update = '';
}

tri this
$(document).ready(function(){
$(document).on('keydown',function(e){
// content
});
});

<script type="text/javascript">
function call(direction) {
$.ajax({ url: '/' + direction });
}
var update, direction, key = null;
document.onkeydown = function (event) {
var key_press = String.fromCharCode(event.keyCode);
var key_code = event.keyCode;
if (key_press == "W" && key != "W") {
key = "W";
direction = 'down';
update = setInterval(function () { call(direction); }, 1000);
} else if (key_press == "S" && key != "S") {
direction = 'up';
key = "S";
update = setInterval(function () { call(direction); }, 1000);
}
}
document.onkeyup = function (event) {
clearInterval(update);
}
</script>

It is something close to how a debounce function works, here's my attempt to solve your question:
function debounce(callback, ms){
var timeOutId;
window.addEventListener('keydown', function(evt){
var key = String.fromCharCode(evt.keyCode);
if(['W','S'].indexOf(key) !== -1 && !timeOutId){
timeOutId = setTimeout(function(){
callback(evt);
timeOutId = null;
}, ms);
}
});
window.addEventListener('keyup', function(evt){
clearTimeout(timeOutId);
});
}
debounce(function(){ /* your function */}, 1000);
Demo on JSFiddle.

Related

stop setinterval function when i hit the spacebar

I have a question, I'd like to stop the setinterval function when I hit the space bar, this script doesnt work, what is the mistake? thanks
window.onload = function(){
var button=document.getElementsByClassName('btn btn-primary')[0];
setInterval(function(){
button.click();
if(event.keyCode == 32 ){
return;
}
}, 1000);
}
You just need to listen for keyup event, then check if the key was the spacebar, if so, you clear the interval using it's id.
window.onload = function() {
var button = document.getElementsByClassName('btn btn-primary')[0];
var intervalId = setInterval(function() {
button.click();
}, 1000);
document.body.onkeyup = function(e){
if(e.keyCode == 32) clearInterval(intervalId)
}
}
This is the answer:
window.onload = function(){
var button=document.getElementsByClassName('btn,btn-primary')[0];
let a=setInterval(frame, 1000);
function frame(){
button.click();
if(event.keyCode == 32 ){
clearInterval(a);
return;
}
}
}
I think something like this :
window.onload = function(){
var button=document.getElementsByClassName('btn btn-primary')[0];
var a = setInterval(function(){
button.click();
if(event.keyCode == 32 ){
clearInterval(a);
}
}, 1000);
}

How To add automatic scrolling in slider

I want to add automatic scrolling time to my slider code but unable to do it can you please suggest me something to help me out with the code to make this slider slide automatic with a set interval of time.
'use strict';
$(document).ready(function () {
var $slides = $('.con__slide').length,
topAnimSpd = 650,
textAnimSpd = 1000,
nextSlideSpd = topAnimSpd + textAnimSpd,
animating = true,
animTime = 4000,
curSlide = 1,
nextSlide,
scrolledUp;
setTimeout(function () {
animating = false;
}, 2300);
//navigation up function
function navigateUp() {
if (curSlide > 1) {
scrolledUp = true;
pagination(curSlide);
curSlide--;
}
}
//navigation down function
function navigateDown() {
if (curSlide < $slides) {
scrolledUp = false;
pagination(curSlide);
curSlide++;
console.log(curSlide);
}
}
$(window).on('load', function () {
$('.con__slide--1').addClass('active');
});
//pagination function
function pagination(slide, target) {
animating = true;
// Check if pagination was triggered by scroll/keys/arrows or direct click. If scroll/keys/arrows then check if scrolling was up or down.
if (target === undefined) {
nextSlide = scrolledUp ? slide - 1 : slide + 1;
} else {
nextSlide = target;
}
////////// Slides //////////
$('.con__slide--' + slide).removeClass('active');
setTimeout(function () {
$('.con__slide--' + nextSlide).addClass('active');
}, nextSlideSpd);
////////// Nav //////////
$('.con__nav-item--' + slide).removeClass('nav-active');
$('.con__nav-item--' + nextSlide).addClass('nav-active');
setTimeout(function () {
animating = false;
}, animTime);
}
// Mouse wheel trigger
$(document).on('mousewheel DOMMouseScroll', function (e) {
var delta = e.originalEvent.wheelDelta;
if (animating) return;
// Mouse Up
if (delta > 0 || e.originalEvent.detail < 0) {
navigateUp();
} else {
navigateDown();
}
});
// Direct trigger
$(document).on("click", ".con__nav-item:not(.nav-active)", function () {
// Essential to convert target to a number with +, so curSlide would be a number
var target = +$(this).attr('data-target');
if (animating) return;
pagination(curSlide, target);
curSlide = target;
});
// Arrow trigger
$(document).on('click', '.con__nav-scroll', function () {
var target = $(this).attr('data-target');
if (animating) return;
if (target === 'up') {
navigateUp();
} else {
navigateDown();
}
});
// Key trigger
$(document).on("keydown", function (e) {
if (animating) return;
if (e.which === 38) {
navigateUp();
} else if (e.which === 40) {
navigateDown();
}
});
var topLink = $(".con__slide--4-top-h-link"),
botLink = $(".con__slide--4-bot-h-link");
$(".con__slide--4-top-h-link, .con__slide--4-bot-h-link").on({
mouseenter: function mouseenter() {
topLink.css('text-decoration', 'underline');
botLink.css('text-decoration', 'underline');
},
mouseleave: function mouseleave() {
topLink.css('text-decoration', 'none');
botLink.css('text-decoration', 'none');
}
});
});
Hope you understand the above code if you have any query in it feel free to ask me and please help me out as soon as possible.
Added setInterval in your code.
setInterval(() => {
if (curSlide >= $slides){
if (animating) return;
pagination(4, 1);
curSlide = 1;
}
else
navigateDown();
}, 10000);
Check updated fiddle.
update below navigateDown code.
//navigation down function
function navigateDown() {
if (curSlide < $slides) {
scrolledUp = false;
pagination(curSlide);
curSlide++;
console.log(curSlide);
}else{
curSlide=1;
pagination(4,1)
}
}
Add this below line
setInterval(navigateDown,7000);

javascript shortcut key / stop Interval function

i make a shortcut key for javascript function . i set the S key for start this and i so set the Z key for clear Interval function but im tired about this and when press Z key the Interval doesnt stop :(
var isCtrl = false;
document.onkeydown=function(e){
if(e.which == 83) {
var elem = document.elementFromPoint( cursorX,cursorY );
elem.addEventListener('click', function() {
console.log('clicked')
}, false);
var support = true;
try {
if (new MouseEvent('click', {bubbles: false}).bubbles !== false) {
support = false;
} else if (new MouseEvent('click', {bubbles: true}).bubbles !== true) {
support = false;
}
} catch (e) {
support = false;
}
var refreshIntervalId = setInterval(function() {
if (support) {
var event = new MouseEvent('click');
}else{
var event = document.createEvent('Event');
event.initEvent('click', true, true);
}
elem.dispatchEvent(event);
},10);
var cursorX;
var cursorY;
cursorX = 0; cursorY = 0;
document.onmousemove = function(e){
cursorX = e.clientX;
cursorY = e.clientY;
elem = document.elementFromPoint(e.clientX, e.clientY);
}
if(e.which == 90) {
clearInterval(refreshIntervalId);
}
}
}
help me i want to press Z key and Interval stop but i can`t ...
UPDATE : this code work correctly . use S key for start and Z key for stop the function .
var elem = document.elementFromPoint( cursorX,cursorY );
elem.addEventListener('click', function() {
console.log('clicked')
}, false);
var support = true;
try {
if (new MouseEvent('click', {bubbles: false}).bubbles !== false) {
support = false;
} else if (new MouseEvent('click', {bubbles: true}).bubbles !== true) {
support = false;
}
} catch (e) {
support = false;
}
var cursorX;
var cursorY;
cursorX = 0; cursorY = 0;
document.onmousemove = function(e){
cursorX = e.clientX;
cursorY = e.clientY;
elem = document.elementFromPoint(e.clientX, e.clientY);
}
var refreshIntervalId;
window.addEventListener("onkeydown", keyDown,true);
window.addEventListener("keydown", keyDown);
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
start();
break;
case 90:
stop();
break;
}
}
function start() {
stop();
refreshIntervalId = setInterval(function() {
if (support) {
var event = new MouseEvent('click');
}else{
var event = document.createEvent('Event');
event.initEvent('click', true, true);
}
elem.dispatchEvent(event);
},1000);
}
function stop() {
if (refreshIntervalId != null) {
clearInterval(refreshIntervalId);
refreshIntervalId = null;
}
}
You also have to code it in a way to avoid starting the timer more than once. You should construct it more like this (move the var for the timer outside the function):
var refreshIntervalId;
window.addEventListener("onkeydown", keyDown,true);
window.addEventListener("keydown", keyDown);
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
start();
break;
case 90:
stop();
break;
}
}
function start() {
stop();
refreshIntervalId = setInterval(function() {
// code...
},10);
}
function stop() {
if (refreshIntervalId != null) {
clearInterval(refreshIntervalId);
refreshIntervalId = null;
}
}
You doesn't seem to make an event to listen to keypress.
jQuery:
$(window).keypress(function(e) {
if (e.which == 90) {
clearInterval(refreshIntervalId);
}
});
Vanilla JS:
var keyEvent = function (e) {
if (e.which == 90) {
clearInterval(refreshIntervalId);
}
};
window.addEventListener('keypress', keyEvent);

get keycode with shiftkey

I want to get keyCode if they are pressed with shift Key,
for ex. I press a and then b. Then I want to store it in one array like this [shiftkey,65,66] please suggest me if this is possible or I am going wrong.
You can try this sanjay:
<input id="down" type="text"/>
var your_array = [];
document.onkeydown = function (e) {
var keyPress;
if (typeof event !== 'undefined') {
keyPress = this.value + String.fromCharCode(e.keyCode);
}
else if (e) {
keyPress = e.which;
}
if(keyPress == '16'){
keyPress = 'shift';
}
your_array.push(keyPress);
alert(your_array);
// returns [shift,65,66];
return false; // Prevents the default action
};
var a = [];
var wait = true;
window.onkeydown = function (e) {
if (wait) {
if (a[0] != e.keyCode) { a[0] = e.keyCode; }
}
wait = false;
window.addEventListener('keyup', key_up, false);
}
function key_up(e) {
a[1] = e.keyCode;
if (a[0] == a[1]) { a = []; }
wait = true;
window.removeEventListener('keyup', key_up, false);
console.log(a);
alert(a);
}
var pressedKeysSeries = [];
$(document).on('keyup', function (e) { pressedKeysSeries = []; });
$(document).on('keydown', function (e) {
if (e.shiftKey && pressedKeysSeries.indexOf(e.key) === -1) {
pressedKeysSeries.push(e.key);
}
console.log(pressedKeysSeries);
});

Clearing setTimeout issues

I'm trying to set "mouseactive" to true less than a second after a key command, but I would like to cancel that action if the key is pressed within that time period. However I can't seem to figure out how to do this. This is what I have...
$(window).keydown(function(e) {
if (e.keyCode == 40) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
var t = setTimeout("mouseActive()",800);
} else if (e.keyCode == 38) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
var t = setTimeout("mouseActive()",800);
}
});
function mouseActive() {
mouseactive = true;
}
But this doesn't work, it doesn't set mouseactive back to true... can anyone tell me what I'm doing wrong here?
Edit: Cleaned up redundant code.
More Edits: Make sure your var t is defined outside any closure including $(document).ready. See below,
var t = null;
$(document).ready(function () {
//..below code except for var t = null
});
Declare var t outside the handler.
var t = null;
$(window).keydown(function(e) {
e.preventDefault();
if (e.keyCode == 40) {
mouseactive = false;
} else if (e.keyCode == 38) {
mouseactive = false;
}
if (t != null) clearTimeout(t);
t = setTimeout(mouseActive, 800);
});
function mouseActive() {
mouseactive = true;
}
Your problem is that t is not in scope the 2nd time the function runs. You need to make t a global variable .
var t;
$(window).keydown(function(e) {
if (e.keyCode == 40) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
t = setTimeout(mouseActive,800);
} else if (e.keyCode == 38) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
t = setTimeout(mouseActive,800);
}
});
function mouseActive() {
mouseactive = true;
}
P.S. Don't pass strings to setTimeout, pass functions. It uses eval when you pass strings.
you are redeclaring "t" all the time, try this:
var t = null;
$(window).keydown(function(e) {
if (e.keyCode == 40) {
e.preventDefault();
mouseactive = false;
if(t != null)
{
clearTimeout(t);
}
t = setTimeout("mouseActive()",800);
} else if (e.keyCode == 38) {
e.preventDefault();
mouseactive = false;
if(t != null)
{
clearTimeout(t);
}
t = setTimeout("mouseActive()",800);
}
});
function mouseActive() {
mouseactive = true;
}

Categories

Resources