Javascript Timer for a maze game - javascript

Hello everyone I was wondering how to put a timer into javascript that will count up. I am trying to make a maze game that counts the time that it takes for a user to get to the finish however I can't figure it out. If you have any suggestions let me know, thanks.

You will want to use setInterval and clearInterval when the game is done. You set the setInterval inside of a variable so you can later reference it in clearInterval
// Increase the game timer by 1 second
var gameTimer = window.setInterval(function() {
// Increase your timer here
}, 1000);
// Clears timer
function clearTimer() {
clearInterval(gameTimer)
}

Related

JS How to count seconds to make bot do an operation every second

I am trying to make a cookie clicker game, and one item that you can get in shop is a bot where it adds x amount of credits to your current amount of credits every second. I want to be able to make multiple of these bots with variations, so not sure if setInterval would be usable in this case. How can I make this?
Note: The timer only starts when a variable is turned to false, so the timer shouldn't start when the app is opened.
P.S. I am using React
let bought = false
const [credits, setCredits] = useState
if (bought) {
For every second {
setCredits(credits+1)
}
}
I think you have to calculate seconds after each reaction on click,
you should use setInterval() in JavaScript function.
Example --
let time = document.getElementById("time");
function clock(){
let date = new Date();
let clocktime = (date.toString().split('G')[0]);
time.innerHTML = `${clocktime}`;
}
setInterval(clock, 1000);
First target an element then change its text to this function's output, and give time here in setInterval() function, for how many seconds you want to repeat that function (for how many seconds)

setTimeout function is out of sync

I am just finishing up a simon says game written with javascript/jquery. Everything is working okay, except for the playback sequence of simon after the second round. What happens is the new random button that simon presses decides to play as the second button in the playback sequence, when it should only be last (I say only because it does play at the end as well). I figure there is a discrepancy between the setTimeout and setInterval, but I am clueless as to what it is. Any ideas as to why this is happening? Here is my codepen for good measure: http://codepen.io/vinnyA3/pen/avvGbM?editors=001
(Press on, then start to start the game)
function playSimonSequence() {
var i = 0;
var myInterval = setInterval(function(){
//send in the correct button name and url to add the button pressed effect
lightsAndSounds(buttonsAndUrls[simonArray[i]].button, buttonsAndUrls[simonArray[i]].url);
++i;
if(i === simonArray.length){clearInterval(myInterval);}
},1500);
//this is running at the wrong time
setTimeout(randomButtonPress, 2210);
}; //end simon sequence
You have a 1500ms interval timer and a 2210ms single timer running at the same time. You should see the first interval at 1500ms, the single timer at 2210ms and then the second interval timer at 3000ms and so on. That's how your code has it specified.
Both your timers are running at the same time.
Javascript does not wait to run your setTimeout() until all the intervals are done. Instead, both timers are scheduled for their future time slot immediately and the run together.
If you want the setTimeout() to run after you clear the interval, then put the setTimeout() in the block of code where you call clearInterval().

javascript reset an interval

I need to be able to call this function to reset the interval.
I know this has been asked before. But the answer given at
Javascript - Reset setInterval back to 0
is not working for me.
Here is the code that I tried:
function startTimer(){
clearInterval(interval);
var interval = setInterval(function(){
advanceSlide();
}, 5000);
};
I call that at the beginning of my page to start a slideshow that changes every 5 seconds. and I use this code to call it again, witch I expected would reset that 5 seconds.
onclick=startTimer();>
The onclick does one other thing too, but this is what is not working. The other action takes place but the interval does not change, its still going based off the same portion of 5 seconds that was left before I clicked.
You need to declare the variable outside the function...
var interval;
function startTimer() {
clearInterval(interval);
interval = setInterval(advanceSlide, 5000);
}
Otherwise it is lost when the function exits.

how to create a timer which triggers an event after 30 seconds in javascript?

I am working on a module in which there is a requirement to show a timer which shows only seconds. The timer must start from 30 and keep on decrementing down to 0; and after that fire some action and again start from 30. How can I achieve this in javascript?
There you go :)
var timer = 30;
function decrementAfter1Second(){
setTimeout(function(){
timer--;
if(timer==0){
doWhateverYouWantAfter30Seconds();
timer = 30;
}
decrementAfter1Second();
}, 1000);
}
decrementAfter1Second();
Now next time you want to do something in javascript don't be a slacker and read something about the language first ;) because right now i'm assuming you either don't know how to program or you don't know how to use google.
You could use setTimeout and clearTimeout. Have the timeout fire every 1 second and then invoke clearTimeout when seconds == 0.
You can find examples of both functions here.

Javascript SetInterval timing issue, total time

base ={time:0};
var loop = 0;
setInterval(function(){
if(base.time === 9000){
move();
base.time = 0;
}
base.time ++;
},1);
Shouldn't the move(); function occur every 9s? I timed it and its much less, why is that?
setInterval will not run every millisecond. There is a minimum possible interval that is longer than that.
If you want something to run in nine seconds, you should use setTimeout() for 9 seconds. Plus your code doesn't reset base.time back to zero so it would only match 9000 once anyway.
If you want it to run every 9 seconds, then you can use setInterval(handler, 9000) or you can use setTimeout(handler, 9000) and then set the next setTimeout in your handler function.
This will execute move() every nine seconds:
var intervalTimer = setInterval(function(){
move();
}, 9000);
Here's a useful article on the topic: http://www.adequatelygood.com/2010/2/Minimum-Timer-Intervals-in-JavaScript.
To reset the time back to 9 seconds when a button is clicked use this code:
var intervalTimer;
function startTimer() {
intervalTimer = setInterval(function(){
move();
}, 9000);
}
function handleClick() {
clearInterval(intervalTimer); // stop currently running interval
startTimer();
}
startTimer();
See it in action here: http://jsfiddle.net/jfriend00/sF2by/.
Intervals are easy as pie!
var move = function(){
alert("move!");
};
setInterval(move, 9000);
See it work here on jsFiddle
You can't count on setInterval actually running every 1 ms. If the CPU is used for another process, it might not run for 1 second. Instead, use one of the following:
function move() {
// Do stuff.
}
// The obvious solution.
// Certain browsers (Chrome) may put the script in "inactive" mode which will
// pause setInterval code. This means move will be run too few times, if you
// actually depend on it being called X times for Y time.
setInterval(move, 9000);
// The other solution.
// Get the delta between each loop and run the move loop as necessary.
// WARNING: This is not efficient, and you should only use this if you have a
// good reason to do so.
// EXTRA WARNING: This code is actually retarded in its current form. It's just
// here to show you how you'd do it. Since you didn't post your
// original problem, it's hard to know what you're really after.
var time = +new Date, frequency = 9000;
setInterval(function () {
var dt = new Date - time;
// Check if we've waited long enough.
if (dt >= frequency) {
// If the process hangs for 20 seconds, this value would be 2. Usually,
// it will be 1.
// Also, Chrome will pause interval counters, so if a tab is inactive,
// this count could be really high when the tab gets focus again.
var times = Math.floor(dt / frequency);
console.log('Moving', times, 'time(s)!');
for (var i = 0; i < times; i++) {
move();
}
// Start counting time from the last update.
time += times * frequency;
}
}, 1); // 1 could probably be much higher here. Depends on your use case.
You wrote in a comment that there is a button which resets the time, and that's why you don't want to just setTimeout for the full delay. Here's how to handle that:
var running;
function start() {
clearInterval(running);
running = clearInterval(function () {
move();
}, 9000);
}
Every time start() is called, the time will be reset to 9 seconds from now, and if 9 seconds elapse, move() will be called and another 9-second interval will start. If you don't actually want it to happen repeatedly, just use setTimeout instead.
The key is using clearInterval (or clearTimeout) to cancel your previous 9-second-delay and start a new one. It is harmless to call clearInterval with a junk value.

Categories