stop setinterval function when i hit the spacebar - javascript

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);
}

Related

Event when space is pressing, only one time

I have some issues: I have this : (in a function..)
var space = 0;
setInterval(space, 20);
var keys = {}
$(document).keydown(function(e) {
keys[e.keyCode] = true;
});
$(document).keyup(function(e) {
delete keys[e.keyCode];
});
function space() {
for (var direction in keys) {
if (!keys.hasOwnProperty(direction)) continue;
if (direction == 32) {
space++;
console.log(space);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
32 == Space key, but I saw in the console that space is pressed 3 times (space == 3), keyup keypress and keydown (I think), how can I have just "space = 1" when space is pressed ?
What seems to be happening is that since it's running every 20 ms, as you hold down the space bar the space function is continuously incrementing the count. I added a flag to prevent another execution until the key is released and it works fine. Really you should just use the keypress event and check there if the keyCode === 32 to track your count. Fewer events will be fired. If you want to see what was happening you can comment out the flag and check the console.
var spaceCount = 0;
var running = false;
var keys = {}
$(document).keydown(function(e) {
console.log("keycode", e.keyCode);
keys[e.keyCode] = true;
});
$(document).keyup(function(e) {
console.log("keyup")
delete keys[e.keyCode];
running = false;
});
function space() {
if(running) return;
for (var direction in keys) {
running = true;
console.log(direction);
if (!keys.hasOwnProperty(direction)) continue;
if (direction == 32) {
spaceCount++;
console.log("count: " + spaceCount);
console.log(keys);
}
}
}
setInterval(space, 20);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I hope that will be helpful:
var space = 0;
var keys = {};
var keys2 = {};
$(document).keydown(function(e) {
keys[e.keyCode] = true;
});
$(document).keyup(function(e) {
keys[e.keyCode] = false;
});
setInterval(function(){spacing()}, 20);
function spacing() {
if (keys[32] && !keys2[32])
{
space++;
keys2[32] = true;
}
else if(!keys[32])
{
keys2[32] = false;
}
console.log(space);
}

How can I change the var of a javascript function by pressing a key on the keyboard?

I have a piece of code here and I want to be able to press a key (f.i. the "1" key) so var isRunning = false. When I press another key (f.i. the "2" key) var isRunning should change back to isRunning = true.
It needs to be as simple as possible (javascript/html), no jquery. I just want to alter the value of this var with a definable keystroke.
This is the code:
<script type="text/javascript">
var pages=[];
pages[0]="page0.html"
pages[1]="page1.html"
pages[2]="page2.html"
var time = 33000;
var currentIndex = 0;
var isRunning = true;
function pageChange() {
if(isRunning){
if(currentIndex == 0){
pages = shuffle(pages);
console.log(pages);
currentIndex = pages.length;
}
currentIndex--;
document.getElementById("frame").src=pages[currentIndex];
console.log(currentIndex);
}
setTimeout(function() { pageChange(); }, time);
};
window.onload = function(){
pageChange();
}
</script>
This Should do the trick ;)
document.addEventListener('keydown', function(event) {
if(event.keyCode == 49) { //keycode 49 is '1'
isRunning = false;
}
else if(event.keyCode == 50) { //keycode 50 is '2'
isRunning = true;
}
});
Since your isRunning is in global scope, you can just catch a keydown event for the number keys. For example if you want to catch the event on the whole page, go like this:
window.onkeydown = function(e){
switch(e.keyCode){
case 49:
case 97:
isRunning = false;
break;
case 50:
case 98:
isRunning = true;
break;
}
}

Javascript setTimeout not working | onkeydown

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.

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;
}

Javascript on second keypress

I've been wondering if there was a simple way to detect if a user presses the same character on the keyboard twice within one second. I've written some code that kind of works but it's unreliable.
var escapeCount = 0;
function reset() {
escapeCount = 0;
setTimeout('reset();', 1000);
}
window.onload = function() {
reset();
};
document.onkeyup = function(e) {
if (!e) var e = window.event;
var code = e.keyCode ? e.keyCode : e.which;
if (code == 27) escapeCount +=1;
if (escapeCount == 2) {
// stuff on second escape
}
};
Is there a better way to do this? Thanks
It would make sense to reset after 1 second has passed since the last character was pressed. Example:
var lastChar = -1;
document.onkeyup = function(e) {
if (!e) var e = window.event;
var code = e.keyCode ? e.keyCode : e.which;
if (lastChar == code) {
// Same key was pressed twice in a row within 1 second.
} else {
lastChar = code;
setTimeout(function() {lastChar = -1;}, 1000);
}
};
Your timer resets every second, so you not only have to press Escape again within a second of the last Escape, but that also has to have no timeout in between the presses.
It's probably easier to forget the timeout and just remember the time of the last keypress instead:
var lastescapetime= null;
document.onkeyup= function(event) {
if (event===undefined) event= window.event;
if (event.keyCode===27) {
var now= new Date().getTime();
if (lastescapetime!==null && now<lastescapetime+1000) {
alert('You double-escaped!');
lastescapetime= null;
} else {
lastescapetime= now;
}
} else {
lastescapetime= null;
}
};

Categories

Resources