Clear interval not working on javascript timer - javascript

Here is my code
document.addEventListener("keydown", move);
function move(e) {
switch (e.keyCode) {
case 37:
x = x - speed;
break;
case 38:
// up key pressed
y = y - speed
break;
case 39:
x = x + speed
break;
case 40:
y = y + speed
break;
case 32:
if (iTouched == true) {
startCounter();
}
break;
}
sendData();
}
document.addEventListener("keyup", getStuff);
function getStuff(e) {
switch (e.keyCode) {
case 32:
if (iTouched == true) {
shoot();
}
break;
}
}
function startCounter() {
function count() {
time += 1
console.log(time)
}
interval = setInterval(count, 100)
}
function shoot() {
clearInterval(interval)
}
The startCounter() function is triggered by a keydown event listener and the shoot() function is triggered by a keyup event listener. For some reason the setInterval will not stop when I lift the key up. The shoot() function works with other commands like an alert() just not the clearInterval(). Am I doing something wrong? Thanks!

Keydown fires multiple times as you hold down the key.
var bod = document.body;
bod.addEventListener("keydown", () => console.log('keydown', new Date()))
bod.addEventListener("keyup", () => console.log('keyup', new Date()))
So you create more than one interval so you overwrite the last one. So you need to clear the interval before you create a new one
if (interval) clearInterval(interval)
interval = setInterval(count, 100)
or do not create one if it exists
if (!interval) {
interval = setInterval(count, 100)
}
and when you clear it
function shoot() {
clearInterval(interval)
interval = null
}

Related

setInterval() only fires once

var x = 0;
window.addEventListener("keydown", function(e) {
switch (e.key) {
case "ArrowLeft":
setInterval(changeValue, 1000, "up");
break;
case "ArrowRight":
setInterval(changeValue, 1000, "down");
break;
}
})
function changeValue(direction) {
switch (direction) {
case "up":
x += 10;
console.log(x);
break;
case "down":
x -= 10;
console.log(x);
break;
}
}
I was expecting my code to keep adding or subtracting 10 from x every second depending on what arrow key the user has pressed. However, setInterval only seems to fire once, and I can't figure out why.
A way to do what you are looking for:
var
conterVal = 0
, addValue = -10
, refIntv = null
;
bt_tenMoreLess.onclick =_=>
{
addValue = -addValue
if (!refIntv)
{
counter.textContent = conterVal += addValue
refIntv = setInterval( changeValue , 1000)
bt_stop.disabled = false
}
}
bt_stop.onclick =_=>
{
clearInterval( refIntv )
refIntv = null
bt_stop.disabled = true
}
function changeValue()
{ counter.textContent = conterVal += addValue }
<p id="counter">0</p>
<button id="bt_tenMoreLess">count ± 10</button>
<button id="bt_stop" disabled >stop</button>

angular 4 setinterval pausing when switch tab

My setInterval timer is pausing when leave the tab and resume when switch back to the tab I want solution to make it keep counting when the tab is switched back
here is GIF picture shows what happen
here is my code:
startCountDown(time) {
clearInterval(this.countDownInterval);
this.timeLeft = time * 100;
if (time === 0) {
return;
}
this.countDownInterval = setInterval(() => {
this.timeLeft -= 1;
if (this.timeLeft === 0) {
clearInterval(this.countDownInterval);
}
}, 10);
}
updateTimer() {
if (this.timeLeft > 0) {
$('.rolling').fadeIn(200);
$('.rolling-inner').html('<div>' + (this.timeLeft / 100).toFixed(2).replace('.', ':') + '</div>');
} else {
$('.rolling').fadeOut(200);
}
}
set timeLeft(x) {
this._timeLeft = x;
this.updateTimer();
}
get timeLeft() {
return this._timeLeft;
}
Setinterval is not misbehaving , This is what it's property . But you can track the tab selection action and add the pending idle duration with existing time.
This is the code to track the tab selection and blur
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) {
switch (e.type) {
case "blur": break;
case "focus": break;
}
}
$(this).data("prevType", e.type);
})

Showing different pictures within 0.08 seconds timeout

I have this code which is supposed to show 24 images within a 0.08333 seconds interval. However it is only showing the last image.
HTML:
<!DOCTYPE html><html><head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><script type="text/javascript" src="script.js"></script><title>page</title></head><body>
<img src="untitled.0001.jpg">
</body></html>
In javascript:
$(document).ready(function () {
$(document).keydown(function(e) {
switch(e.which) {
case 39: // right
for (var i = 1; i != 24; i++) {
setTimeout(function(){
$( "img" ).replaceWith( "<img src='image.000"+ i +".jpg'>");
},83);
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});
How can I make it show all images within a timeout of 0.08333 seconds
Update: I tried solving it and came up with this:
$(document).ready(function () {
$(document).keydown(function(e) {
switch(e.which) {
case 39: // right
var count = 1;
while (count!=24) {
var waiting = 83 * count;
setTimeout(function() {$( "img" ).replaceWith( "<img src='avatar/walk/HumanWalk.000"+ count +".jpg'>");}, waiting);
count+=1;
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});
Why is it still not working and showing last image only?
Use setInterval for such a case:
$(document).keydown(function(e) {
switch (e.which) {
case 39:
var c = 0;
var interval = setInterval(function() {
// set the source of your image to
// 'image.000' + (c++ -1) + '.jpg'
}, 83);
if (c === 24) clearInterval(interval);
}
});
Try this code
$(document).ready(function() {
$(document).keydown(function(e) {
switch (e.which) {
case 39: // right
for (var i = 1; i != 24; i++) {
(function(x) {
setTimeout(function() {
$("img").replaceWith("<img src='image.000" + x + ".jpg'>");
}, i*83);
})(i);
}
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});

how to set only one key for stop/start setInterval function

I have function for stop and start the setInterval with key .
it's starts with S key and stops with Z key .
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;
}
}
So how can i set only Z key for start and stop the SetInterval ??
for example i press Z key and it starts then i press Z key again and it stops !
anyone can help me ?
Modify your code like below,
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 90:
if(refreshIntervalId) {
stop();
}
else {
start();
}
break;
}
}
Check if refreshIntervalId is a truthy value. If it is then stop the interval else start it.
var boolStart = false;
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
if(!boolStart){
start();
}else{
stop();
}
break;
}
}
function start() {
stop();
boolStart = true;
..
}
function stop() {
boolStart = false;
....
}
EDIT 1:
You can do in this way also.
var boolStart = false;
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
//;
boolStart = !boolStart;
if (!boolStart) {
start();
} else {
stop();
}
break;
}
}

Jquery: count using setInterval

Im trying to create two counter when I press downKey I want to counter1 start counting and when I press keyLeft I want to stop the first counter and start counter2 .... I know that I need to use clearInterval() function but I dont know where I need to use it, here is a JSFiddle
to see what I mean
html:
<div id="left"></div>
<div id="down"></div>
js:
$('body').keydown(function (e) {
switch (e.which) {
case 39:
clearInterval(down_move);
var i=0;
var right_move = setInterval(function(){
$('#left').html(i);
i++
}, 1000)
break;
case 40:
clearInterval(right_move);
var j = 0;
var down_move = setInterval(function(){
$('#down').html(j)
j++;
}, 1000);
break;
default:
}
e.preventDefault();
});
You need to declare down_move and right_move outside of keydown:
var right_move, down_move;
$('body').keydown(function (e) {
switch (e.which) {
case 39:
clearInterval(down_move);
var i=0;
right_move = setInterval(function(){
$('#left').html(i);
i++
}, 1000)
break;
case 40:
clearInterval(right_move);
var j = 0;
down_move = setInterval(function(){
$('#down').html(j)
j++;
}, 1000);
break;
default:
}
e.preventDefault();
});
it seems like a scope issue, here is how I would make it:
updated fiddle
var Interval = function(intervalFunc, selector){
var interval;
this.start = function(){
interval = setInterval(intervalFunc, 1000);
},
this.stop = function(){
clearInterval(interval);
}
}
var i = 0;
var rightBtnInterval = new Interval(function downInterval(){
$('#right').html(i)
i++;
});
var j = 0;
var downBtnInterval = new Interval(function downInterval(){
$('#down').html(j)
j++;
});
$('body').keydown(function (e) {
switch (e.which) {
case 39:
rightBtnInterval.stop();
downBtnInterval.start();
break;
case 40:
downBtnInterval.stop();
rightBtnInterval.start();
break;
default:
}
e.preventDefault();
});
You have to store outside of function the interval to stop.
Warning the ascii code of left is 37.
Here is a JSFiddle to see my change:
var storeInterval = null;
$('body').keydown(function (e) {
switch (e.which) {
case 37:
clearInterval(storeInterval);
var i=0;
storeInterval = setInterval(function(){
$('#left').html(i);
i++
}, 1000)
break;
case 40:
clearInterval(storeInterval);
var j = 0;
storeInterval = setInterval(function(){
$('#down').html(j)
j++;
}, 1000);
break;
default:
}
e.preventDefault();
});
<div id="left"></div>
<div id="down"></div>

Categories