I am trying to make a simple game like: www.aimbooster.com to test my javascript knowledge but I have come into a problem. Basically I want to have a timer that counts the amount of time the user has got but I can't use the setInterval method because then the program has to wait a whole second before anything else happens which is not what I want. What I want is this timer process to run in the background. I think this is commonly named as "Threading". How would I go about this?. I'd want something along the lines of:
function startTimer() {
while (stop == false) {
setInterval(function() {time++};1000);
}
}
function startGame() {
startTimer();
//MY GAME STARTS HERE
}
If I do this at the moment, the startTimer function will continually go and I won't be able to do anything else. I want startTimer to be a subproccess while the main process is the game.
while (stop === false) {
setInterval(function() {time++};1000);
}
this is a infinite loop, and you are calling setInterval infinite time and the eventloop doesn't have a chance to pop the callback to the stack to increase the time variable.
I would like to save the timer variable, and use clearInterval to stop the timer
function Game() {
}
Game.prototype.start = function() {
this.timer = setInterval(function() {
// do your stuff
}, 1000);
// start game
}
Game.prototype.stop = function() {
clearInterval(this.timer);
}
You could do something like:
function startTimer() {
setInterval(function() {while (stop == false) time++}, 1000);
}
Related
So from what I have understood, setInterval() is used to call a function on repeat on regular intervals.
So basically it is a loop that executes a function forever periodically.
I am confused as to if I had to stop this execution at one point what would be the way to do it
for eg I am trying to print the message "hey" 3 times after 1 second each, but somehow it is printing it 3 times every second and is going on forever.
What can I do to stop it after a set number of times.
This is the code that I've been trying
var i = 3;
function message() {
console.log("hey");
}
while(i > 0) {
setInterval(message, 1000);
i = i - 1;
}
Your code is executing the setInterval thrice in the while loop, which is not needed.
Actually, setInterval does not work as a function call but actually registers a function to be called at some interval.
The setInterval() method will continue calling the function until clearInterval() i.e it is deregistered or the process is killed.
It should work like this
var i = 3;
var interval = setInterval(message, 1000);
function message() {
if (i === 0) {
clearInterval(interval);
}
console.log("hey");
i = i - 1;
}
To clear a setInterval, use global clearInterval method.
Example:
var timerId = setInterval(func, 500);
.... some code here....
clearInterval(timerId);
What can I do to stop it after a set number of times.
usually you don't use setInterval() for this, you use setTimeout().
Something like
var counter = 0;
function message() {
console.log("hey");
// we trigger the function again after a second, if not already done 3 times
if (counter < 3) {
setTimeout(message, 1000);
}
counter++;
}
// initial startup after a second, could be faster too
setTimeout(message, 1000);
The setInterval function calls the function indefinitely, whereas setTimeout calls the function once only.
Simply use clearInterval once the count runs out.
var i = 3;
function message(){
console.log("hey");
if (--i < 0) {
clearInterval(tmr);
}
}
var tmr = setInterval(message, 1000);
you have to assign that setInterval to a javascript variable to name it what for this setInterval, like this
var messageLog = setInterval(message, 1000);
After, in setInterval message function add this condition to clear the inverval whenever you want to clear.
function message(){
if(i>3) {
clearInterval(messageLog); // clearInterval is a javascript function to clear Intervals.
return null;
}
console.log("hey");
}
You can retrieve the timer when creating and clear it if needed.
var i=3;
var timer = setInterval(message,1000);
function message(){
console.log("hey");
i—-;
if(i==0)
clearInterval(timer)
}
a beginner here too,look for clearInterval method ...
I'am working on a game with the canvas element. The goal is that first time you press a key it start a stopwatch. It should end as soon as the gameoverscreen/winscreen appears.
After the gameoverscreen/winscreen it should work like befor(if press key than start stopwatch)
The problem is that that the function only once called can be.
The Code(the most important part):
function startTime(){
startTime = function(){};
var count = 0;
function stopwatch(){
if(winScreen || gameOver){
count = 0;
} else{
console.log(count++);
}
}
setInterval(stopwatch, 1000);
}
document.addEventListener('keydown', function(event){
startTime();
});
Is there a way to solve that problem?
The cause of your problem is that you are overwriting startTime with an empty function on the second line. The second time you call startTime(), it runs the empty function.
To keep your code clean, your stopwatch shouldn't really check for the win or game over conditions - it should only keep track of the count. The rest of your game code can start and reset the stopwatch whenever those conditions occur. You could have a stopwatch object like this:
var stopwatch = {
count: 0,
intervalId: null,
start: function() {
stopwatch.intervalId = setInterval(function() {
stopwatch.count++;
}, 1000)
},
reset: function() {
if (stopwatch.intervalId) {
clearInterval(stopwatch.intervalId);
stopwatch.intervalId = null;
}
stopwatch.count = 0;
}
}
Then your game can call stopwatch.start() when it starts and stopwatch.reset() when it ends.
Note that it also clears the interval when it resets. Without this, the function inside setInterval would get duplicated every time, causing potential bugs and a memory leak.
So my hmtl eventhandeling button is
<input type="button" value="Stop" onclick="stop()">
and the javascript function stop() is:
function stop()
{
stop.called = true;
}
and I call this function here:
....
var interval = setInterval(function ()
{
// call generation again for each generation, passing in the previous generations best offspring
best_offspring = generation(best_offspring, characters, amount_offspring, mutation_rate, target_text);
document.getElementById("output_text").value = best_offspring;
document.getElementById("generations").value = generations;
if (score_met)
{
clearInterval(interval);
}
}, delay);
if (stop.called)
{
return;
}
// so that we know that the program has been run atleast once
start = true;
}
Do you need more of the code?
Anyway, what I want is to stop the execution when the function is called. But my interval loop continues even though the stop() function is called. I have also tried to put the ´if(stop.called)insidevar interval` loop. But that didnt work either.
Any ideas? Do I need to provide more info?
if (stop.called)
{
clearInterval(interval);
}
¿?
var interval = setInterval(function ()
{
// call generation again for each generation, passing in the previous generations best offspring
best_offspring = generation(best_offspring, characters, amount_offspring, mutation_rate, target_text);
document.getElementById("output_text").value = best_offspring;
document.getElementById("generations").value = generations;
if (score_met || stop.called)
{
clearInterval(interval);
}
}, delay);
if (stop.called)
{
clearInterval(interval);
return;
}
// so that we know that the program has been run atleast once
start = true;
}
SetInterval returns an Id so you can simply call clearInterval(id);. Return break etc. Doesnt work because it is not really a loop like for and while.
I am trying to get a function to run 10 times with a pause inbetween each run, yet when I try to it repeats the function infinite times then after 10 times it pauses, and so on. Right now this is the code with the problem:
for(i=0;i<10;i++) {
console.log(i);
interval = setInterval(function() {console.log("Function ran");}, 1000);
}
window.clearInterval(interval);
Console:0123456789Function ran["Function ran" is repeated infinite times after "9"]
interval = setInterval(function() {console.log("Function ran");}, 1000);
This line creates a new interval-instance each time, which means you have created 10 intervals. At the end of the loop interval holds the id of the last interval that was created. Hence that's the only one you're clearing, and the other ones are still running.
To cancel the interval, you need to keep track of how many times the function has been invoked. One way you can do that is as follows:
function pauseAndRepeat(delay, iterations, func) {
var i = 0;
var interval = setInterval(function() {
func();
if(++i === iterations) {
clearInterval(interval);
}
}, delay);
}
Here we have a function that defines a counter (i) in its local scope. Then it creates an interval using a function that checks the counter to see if it should call your function (func) or clear the interval when it is done. interval will have been set when the interval-handler is actually called. In this case the handler is basically a closure since it is bound to the local scope of pauseAndRepeat.
Then you can invoke the function as follows:
pauseAndRepeat(1000, 10, function() {
console.log("Function ran");
});
This will print out Function ran ten times, pausing for a second each time.
setInterval is expected to run forever, on an interval. Every time you call setInterval here, you have a new infinite loop running your function every 10s, and as others have noted you only are canceling the last one.
You may do better with chained setTimeout calls:
var counter = 0;
function next() {
if (counter < 10) {
counter++;
setTimeout(function() {
console.log("Function ran");
next();
}, 1000);
}
}
next();
This chains delayed functions, setting a timeout for the next one after each runs. You can do something similar with setInterval and cancellation:
var counter = 0;
var intervalId = setInterval(function() {
console.log("Function ran");
if (++counter >= 10) {
clearInterval(intervalId);
}
}, 1000);
In both these cases the key issue is that you trigger the next run or cancel the interval within the callback function, not in synchronous code.
I want to be able to call the function work() every 6 seconds. My jQuery code is
function looper(){
// do something
if (loopcheck) {
setInterval(work,6000);
}
else {
console.log('looper stopped');
}
}
The problem I am running into is that it loops over work twice quickly, and then it will wait for 6 seconds. i tried using setTimeout with similar results.
What could be causing work to be called twice before the delay works?
setInterval should be avoided. If you want work to be repeatedly called every 6 seconds, consider a recursive call to setTimeout instead
function loopWork(){
setTimeout(function () {
work();
loopWork();
}, 6000);
}
Then
function looper(){
// do something
if (loopcheck) {
loopWork()
}
else {
console.log('looper stopped');
}
}
And of course if you ever want to stop this, you'd save the value of the last call to setTimeout, and pass that to clearTimeout
var timeoutId;
timeoutId = setTimeout(function () {
work();
loopWork();
}, 6000);
Then to stop it
clearTimeout(timeoutId);
Use old-style setTimeout()
var i=0;
function work(){
console.log(i++);
}
function runner(){
work();
setTimeout(runner, 6000);
}
runner();
I prefer the following pattern myself I find it easier to follow:
function LoopingFunction() {
// do the work
setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}
And if you want to be able to stop it at any point:
var LoopingFunctionKeepGoing = true;
function LoopingFunction() {
if(!LoopingFunctionKeepGoing) return;
// do the work
setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}
Now you can stop it at any time by setting LoopingFunctionKeepGoing to false.