clearInterval and pausing a game - javascript

this.update = function() {
if (state == "game") {
if (jaws.pressed("p") && !jaws.paused) {
jaws.paused = true;
setTimeout(function() {
var unpause_interval_id = setInterval(function() {
if (jaws.pressed("p") && jaws.paused) {
jaws.paused = false;
clearInterval(unpause_interval_id);
}
});
}, 5000);
}
That is my attempt at pausing a game I'm working on. Basically, when the player pauses, I set a timeout of 5 seconds to a function that checks if the player wants to unpause.
However, I am not being successful at clearing the interval, the clearInterval function isn't work, I'm sure of it from what I've debugged. Any idea of what I'm doing wrong?
Thank you!

How about:
function p_unp()
{
jaws.paused = !jaws.paused;
}
jaws.on_keypress("p", p_unp);

I recommend to remove setInterval function. The while loop instead:
this.update = function() {
if (state == "game") {
if (jaws.pressed("p") && !jaws.paused) {
jaws.paused = true;
while (jaws.paused) {
if (jaws.pressed("p") && jaws.paused) {
jaws.paused = false;
}
}
});
}

Related

SetInterval won't stop running

I have a function that uses setInterval, and it keeps running and it doesn't want to stop. The code I wrote is
let findGrid = setInterval(function () {
if (grid == null) {
grid = $('#QuickEntryGrid').getKendoGrid();
}
else {
clearFindGrid;
console.log("Found Grid");
console.log(grid.dataSource.view());
}
}, 100);
let clearFindGrid = function () {
clearInterval(findGrid);
};
if (grid != null) {
grid.setOptions({
width: (newInnerVerticalWidth - 2) + "px"
});
$("#QuickEntryGrid").find("table").on("keydown", onGridKeydown);
}
It keeps hitting the console.log(grid.dataSource.view());
You must call the funcion with the brakets clearFindGrid()

variable changing to true before setInterval is finished

showMoves is a function made to show flashing for a simon game.
When the flashing lights are over I clear the interval to stop it and then I set game.playerTurn to true so I can click on colors, but game.playerTurn is changing to true as soon as showMoves is activated.
I want game.playerTurn to stay false until the showMoves function is finished showing flashing.
Here are the functions I'm using game.playerTurn in -
game.playerTurn = false;
//for flashing lights
function showMoves() {
let i = 0;
const start = setInterval(function () {
if (i >= game.computerMoves.length) {
clearInterval(start);
game.playerTurn = true;
return;
}
const move = game.computerMoves[i];
setLight(move, true);
setTimeout(setLight.bind(null, move, false), 1000); //Using bind to preset arguments
i++;
}, 2000);
}
function setLight(color, isOn) {
if (isOn) {
sounds[color.id].play();
}
color.style.backgroundColor = isOn ? colors[0].get(color) : colors[1].get(color);
}
//compareMoves is fired everytime I click on a color
function compareMoves(e) {
if (e === game.computerMoves[game.counter]) {
game.counter++;
//This is if all the moves were chosen correctly
if (game.playerMoves.length === game.computerMoves.length && e === game.computerMoves[game.computerMoves.length - 1]) {
simonHTML.displayScore.textContent = ++game.score;
game.playerTurn = false;
resetMoves();
randomMoves(++game.turn);
showMoves();
game.counter = 0;
}
} else if (game.strict) {
//if your move was wrong do this
} else {
game.playerMoves = [];
game.counter = 0;
game.playerTurn = false;
showMoves();
return false;
}
}
I'd appreciate any help with this. Here is a link to the game and all the code https://codepen.io/icewizard/pen/JLBpNQ
Where are you setting game.playerTurn back to false?
function showMoves() {
game.playerTurn = false;
let i = 0;
const start = setInterval(function() {
if (i >= game.computerMoves.length) {
clearInterval(start);
game.playerTurn = true;
return;
}
const move = game.computerMoves[i];
setLight(move, true);
setTimeout(setLight.bind(null, move, false), 1000); //Using bind to preset arguments
i++;
}, 2000);
}
Seems to work for me in the codepen example you provided

How to start and stop checking a condition every few minutes in javascript?

I am developing a javascript application where I have to do this.
Check every 5 seconds that whether the page contains an element with tag.
Once, the tag is detected, then start my video tracking function.
DO NOT check again every 5 seconds that whether the page contains an element with tag - once a tag has been detected and my video tracking function has been started.
Here is my code:
<script>
setInterval(function() {
var myVideo = document.getElementsByTagName('video')[0];
console.log(myVideo);
if (myVideo != null)
{
myVideo.id = 'video-stream';
var colors = new tracking.ColorTracker(['magenta', 'cyan', 'yellow']);
colors.on('track', function(event) {
if (event.data.length === 0) {
// No colors were detected in this frame.
} else {
event.data.forEach(function(rect) {
console.log(rect.x, rect.y, rect.height, rect.width, rect.color);
});
}
});
tracking.track("#video-stream", colors);
}
}, 5000);
</script>
Right now, it just keeps checking even if a tag is detected, So how do I stop it from checking once it if (myVideo != null) condition is fulfilled and it has gotten into it?
Any suggestions will be highly appreciated.
The setInterval function returns a value with you can then use to stop the interval in conjunction with clearInterval, so in your case:
var interval = setInterval(function() {
...
if (myVideo !== null) {
clearInterval(interval)
}
...
}, 5000);
I hope that helps.
Create a function, which calls itself after 5s if the tag doesn't exist:
function testVideo() {
var myVideo = document.getElementsByTagName('video')[0];
console.log(myVideo);
if (myVideo != null) {
myVideo.id = 'video-stream';
var colors = new tracking.ColorTracker(['magenta', 'cyan', 'yellow']);
colors.on('track', function(event) {
if (event.data.length === 0) {
// No colors were detected in this frame.
} else {
event.data.forEach(function(rect) {
console.log(rect.x, rect.y, rect.height, rect.width, rect.color);
});
}
});
tracking.track("#video-stream", colors);
}
else {
setTimeout(test, 5000); //try again in 5s
}
} //testVideo
testVideo(); //call the function
You should define your interval in variable and when you detect the video you should use clearInterval()
https://jsfiddle.net/o127oqjr/
var myInterval = setInterval(function() {
var myVideo = document.getElementsByTagName('video')[0];
console.log(myVideo);
if (myVideo != null)
{
clearInterval(myInterval);
myVideo.id = 'video-stream';
var colors = new tracking.ColorTracker(['magenta', 'cyan', 'yellow']);
colors.on('track', function(event) {
if (event.data.length === 0) {
// No colors were detected in this frame.
} else {
event.data.forEach(function(rect) {
console.log(rect.x, rect.y, rect.height, rect.width, rect.color);
});
}
});
tracking.track("#video-stream", colors);
}
else{
console.log('notFound')
}
}, 5000);

clearInterval doesn't working

var started = false;
function start() {
var timer;
if(started === false) {
timer = setInterval(decrease, 1000);
started = true;
} else {
clearInterval(timer);
console.log("Should Clear");
}
}
The setInterval works but when I run the function again, it prints in the console that it should be removed. But it doesn't.
timer is declared inside your function, so when you call it again, it's a new instance.
Try declaring it outside the function, like this:
var started = false;
var timer;
function start() {
if(started === false) {
timer = setInterval(decrease, 1000);
started = true;
} else {
clearInterval(timer);
console.log("Should Clear");
}
}
timer gets reinitialized every time you call start so the second time you call it, it's not pointing to a timer id to clear.
use like this
var started = false;
var timer;
function start() {
if(started === false) {
timer = setInterval(decrease, 1000);
started = true;
} else {
clearInterval(timer);
console.log("Should Clear");
}
}
Because timer is in the scope of the function. So when you call it the second time, it is in another scope.

clearTimeout not working in recursion function - javascript

Here is the code I am using. When ticks becomes equal to 5 the recursion function should stop clearing the mainThread timeout. Anybody please help.
var mainThread;
var ticks = 0;
function tickTimer() {
clearTimeout(mainThread);
if (ticks >= 5) {
endGame();
}
else {
mainThread = setTimeout(function () {
ticks++;
tickTimer();
}, 1000);
}
}
Let me know if any concerns.
Thank you in advance.
Try this instead:
function tickTimer() {
if (++ticks >= 5) {
clearInterval (mainThread);
endGame();
}
}
var mainThread = setInterval(tickTimer, 1000);
var ticks = 0;
you can try this. all you need to do is clear interval every time tickTimer function is called.
var mainThread = setInterval(tickTimer, 1000);
var ticks = 0;
function tickTimer() {
if (++ticks >= 5) {
clearInterval (mainThread);
endGame();
}
}
Did you declare mainThread ? Like this
var mainThread = null;
function tickTimer() {
clearTimeout(mainThread);
mainThread = null;
if (ticks >= 5) {
endGame();
}
else {
mainThread = setTimeout(function () {
ticks++;
tickTimer();
}, 1000);
}
}
And ticks++ not ticks--
Please try to replace ticks-- to ticks++
I've think just send your timer as argument
function tickTimer(timer) {
timer && clearTimeout(timer);
if (ticks >= 5) {
endGame();
}
else {
var timer = setTimeout(function () {
ticks--;
tickTimer(timer);
}, 1000);
}
}
Don't use global scope )))
I thing you should Initialize variable ticks as the function is triggered.

Categories