Javascript function, need to decrement every 30 secs time elapsed - javascript

I'm trying to make the this.SPAWN_FREQUENCY decrease by 200 after time elapsed reaches 30 seconds, 1 min, 2 min and so on. Basically levels in the game increasing the amount of enemies to defeat. I've tried a load of code and still can't get anything to work.
Any suggestions where to start?
Sorry if I didn't provide enough detail.
function EnemyManager (timer) {
this.enemies = [];
this.SPEED = -5;
this.SPAWN_FREQUENCY = 1300;
this.spawnTimer = 0;
Do I add 'if' statement?

Use setTimeout
(function () {
var interval = 1000*30;
var SPAWN_FREQUENCY = 1300;
timer = function() {
SPAWN_FREQUENCY = SPAWN_FREQUENCY - 200;
//do the rest
console.log(SPAWN_FREQUENCY);
setTimeout(timer, interval);
interval = interval*2;
};
timer();
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

have you tried something like:
function Manager(){
this.SPAWN_FREQUENCY = 1300;
this.inc();
}
Manager.prototype.inc = function(){
var this_store = this;
setTimeout(function(){
this_store.SPAWN_FREQUENCY -= 200;
this_store.inc();
}, 100);
};

Your function:
var element = this;
var spawninterval = window.setInterval(function(){
element.SPAWN_FREQUENCY -= 200;
},30000);
and when you're done, you can call
window.clearInterval(spawninterval);

Related

How to stop a function after ten seconds?

I found this piece of code while trying to find out a way to load a reddit page so that I can use ctrl + f to find a specific post. The problem is that it just keeps scrolling down and loading the pages. I need to find a way to stop it after 10 seconds so that I can take a look at what I loaded. Also I don't know any javascript so I couldn't really find anythig that would help me.
Here is the code
var lastScrollHeight = 0;
function autoScroll() {
var sh = document.documentElement.scrollHeight;
if (sh != lastScrollHeight) {
lastScrollHeight = sh;
document.documentElement.scrollTop = sh;
}
}
window.setInterval(autoScroll, 100);
I just paste that into the firefox console.
The setInterval() function returns an ID, which you can use to stop it.
Just put it in setTimeout() method like this:
var myInterval = setInterval(autoscroll, 100);
setTimeout(function(){ clearInterval(myInterval); }, 10000);
To stop the interval after a certain amount of time use a setTimeout() that calls clearInterval(). Here's a simplified version (with the time reduced to 1 second for demo purposes) that should help:
function autoScroll(){
console.log("running")
}
// save a reference to the interval handle
let interval = window.setInterval(autoScroll, 100);
// cancel interval after 1 second (1000 ms)
setTimeout(() => clearInterval(interval), 1000)
You will simply need to call clearInterval on your looped function to stop it after using a setTimeout set to 10 seconds, here is how you can implement it :
var lastScrollHeight = 0;
function autoScroll() {
var sh = document.documentElement.scrollHeight;
if (sh != lastScrollHeight) {
lastScrollHeight = sh;
document.documentElement.scrollTop = sh;
}
}
const interval = window.setInterval(autoScroll, 100);
window.setTimeout(() => {clearInterval(interval)}, 10000);
....
var intervalID = window.setInterval(autoScroll, 100);
setTimeout(function(){
clearInterval(intervalID);
}, 10000);
You can use setTimeout to call the function until 10s are up.
Here's an immediately-invoked function that calls itself every 100th sec until 10s has been reached.
(function autoScroll(t) {
t = t || 0;
if (t < 10000) {
console.log(t);
setTimeout(autoScroll, 100, t += 100);
}
})();

How to create a counter that increments by 1 every 1-8 seconds(random)

So I think I'm close, but what I've written begins to increment by larger values, and at an increasing speed the longer it runs. I assume this is an issue with the interval not being properly cleared. Please assist in anyway possible.
<html>
<head>
<script type="text/javascript">
function setTimer(){
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
clearInterval(interval);
var interval = setInterval(updateCounter, timer);
}
function updateCounter(){
var counter = document.getElementById("counter");
var count = parseInt(counter.innerHTML);
count++;
counter.innerHTML = count;
setTimer();
}
</script>
</head>
<body style="margin:5%;" onload="setTimer()">
<div id="counter">1</div>
</body>
</html>
Your interval variable is a local variable to setTimer. clearInterval(interval); won't work, because you are passing undefined (the value of interval). It won't throw an error though because of variable hoisting but the value you pass to clearInterval is undefined for sure.
Fix #1:
Declare interval outside setTimer:
var interval;
function setTimer(){
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
clearInterval(interval);
interval = setInterval(updateCounter, timer); // no redeclaring here
}
Fix #2:
Since you are clearing intervals right before setting them again, you could use setTimeout as it perfectly fit your needs:
function setTimer() {
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
setTimeout(updateCounter, timer); // no clearing is needed this time
}
Note:
Your timer variable will be between 1-6 seconds. You said you wanted it to be 1-8, so use:
var timer = (Math.floor(Math.random() * 8) + 1) * 1000;
I don't think the updateCounter method should know it is called from a timer and be responsible for calling setTimer(). What if you want to call the method to update the counter from somewhere else that is not using a timer. Managing the call to updateCounter should be done by the controlling code IMHO.
Also, using setTimeOut() might be better here as you then don't have to manage the intervals.
function setTimer() {
var timer = (((Math.floor(Math.random() * 6)) + 1) * 1000);
setTimeout(function() {
updateCounter();
setTimer();
}, timer)
}
function updateCounter() {
var counter = document.getElementById("counter");
var count = parseInt(counter.innerHTML);
count++;
counter.innerHTML = count;
}
<body style="margin:5%;" onload="setTimer()">
<div id="counter">1</div>
</body>
I would suggest moving setTimer() outside of updateCounter() otherwise you will be creating new intervals everytime you call updateCounter(). Try
function setTimer(){
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
var interval = setInterval(updateCounter, timer);
}
function updateCounter(){
var counter = document.getElementById("counter");
var count = parseInt(counter.innerHTML);
count++;
counter.innerHTML = count;
}
setTimer();
EDIT: removed clearInterval

Changing MS of setInterval depending on a condition

I'm trying to change the speed at which my program will iterate through my array and put info into my text area. But I don't think I understand the functionality of setInterval and setTimeout perfectly, or maybe its something else, I'm very new to JS.
var theStage,getDrop,getSize,time,isChecked,turbo;
function changeFrame(stopper){
if(isChecked === true){
turbo = 50;
}
else{
turbo = 250;
}
time = setInterval(start, turbo);
}
function start(){
var frames = theStage.value.split("=====\n");
var i = 0, l = frames.length;
(function iterator() {
theStage.value = frames[i];
if(++i<l) {
setTimeout(iterator, turbo);
}
})();
};
setTimeout and setInterval are creating a new timer each time you call them. If you want to have one timer, but change how often it's executed, then you need to remove it and "set" with a new time, like this:
var timer = null;
...
// Each time, before creating a new timer, remove the old one.
if (timer !== null)
clearInterval(timer)
timer = setInterval(...);
I think, that your code can be simplified to use only one timer:
var theStage, isChecked, delay;
var frames = theStage.value.split("=====\n");
var progress = 0, l = frames.length;
function changeSpeed() {
if (isChecked)
delay = 50;
else
delay = 250;
}
function processFrame() {
theStage.value = frames[progress];
if (++progress < l)
// Recursively call self until whole list of frames is processed.
setTimeout(processFrame, delay);
}
When you use setTimeout to create recursive function then you don't need to reset timer.

Timer counting faster on second run

I am working on a simple game right now. its almost done except for the timer has a glitch in it and I can't figure out whats doing it. when you push a button, an HTML5 text on the canvas starts to count down from 35 to 0. On the first run it's fine. But if you choose to play again with out refresh the timer starts to countdown faster. here is the code.
var timer = 35;
ctx.fillText("Countdown: " + timer, 320, 32);
function resetReggie(){
reggie.x = canvasWidth / 2;
reggie.y = canvasHeight / 2;
}
//Starts Timer for Timed Game
function timedMsg()
{
resetReggie();
ballsCaught = 0;
timer = 35;
alert('Pick up as many as you can in ' + timer + ' seconds');
countDown();
var t=setTimeout(function() {
var again = confirm("TIMES UP! You Gathered " + ballsCaught + " Balls! Play Again?");
if (again === true){
timedMsg();
resetReggie();
}
if (again === false){
resetReggie();
ballsCaught = 0;
timer = 35;
}
}, timer * 1000);
}
function countDown() {
if (timer != 0){
timer-=1;
setTimeout('countDown()', 1000);
}
}
I think the problem is in the line
}, timer * 1000);
where you have a value that is at most 34 at the time 'timer' is evaluated to set the timeout. Because you initialize it to 35 but then call countDown() which decreases it to 34, then you have a call to confirm() which might let 'timer' decrease even more. As a result the subsequent call to timedMsg() happens a little too soon causing countDown() to be called twice as often. Try the following (I ran it in node) and then change the 4 to 6.
function countDown() {
console.log("Countdown: " + timer, 320, 32);
if (timer != 0) {
timer -= 1;
setTimeout(countDown, 1000);
}
}
function timedMsg() {
timer = 5;
countDown();
var t=setTimeout(function() {
timedMsg();
}, 4 * 1000);
}
timedMsg();
As mentioned in my comment, each time you start a new game, it appears you are decreasing the timeout value. As a result, this reduces the time each time.
Try this:
var timeout = currentTime = 5;
var int = setInterval(function() {
​console.log(currentTime);
currentTime--;
if(currentTime < 0) {
var again = confirm('Play again?');
if(again) {
currentTime = timeout;
}
else {
clearInterval(int);
}
}
}, 1000);​
http://jsfiddle.net/gRoberts/CsyYx/
Look at your console (F12 in Chrome), or update the code to write to the browser to see it working ;)

Javascript - telling setInterval to only fire x amount of times?

Is it possible to limit the amount of times that setInterval will fire in javascript?
You can call clearInterval() after x calls:
var x = 0;
var intervalID = setInterval(function () {
// Your logic here
if (++x === 5) {
window.clearInterval(intervalID);
}
}, 1000);
To avoid global variables, an improvement of the above would be:
function setIntervalX(callback, delay, repetitions) {
var x = 0;
var intervalID = window.setInterval(function () {
callback();
if (++x === repetitions) {
window.clearInterval(intervalID);
}
}, delay);
}
Then you can call the new setInvervalX() function as follows:
// This will be repeated 5 times with 1 second intervals:
setIntervalX(function () {
// Your logic here
}, 1000, 5);
I personally prefer to use setTimeout() spaced out to achieve the same effect
// Set a function to run every "interval" seconds a total of "x" times
var x = 10;
var interval = 1000;
for (var i = 0; i < x; i++) {
setTimeout(function () {
// Do Something
}, i * interval)
}
There's no clean up required with clearInterval()
You can enclose it to avoid variables leaking and it looks pretty clean :)
// Definition
function setIntervalLimited(callback, interval, x) {
for (var i = 0; i < x; i++) {
setTimeout(callback, i * interval);
}
}
// Usage
setIntervalLimited(function() {
console.log('hit'); // => hit...hit...etc (every second, stops after 10)
}, 1000, 10)
You can set a timeout that calls clearInterval.
This should work:
function setTimedInterval(callback, delay, timeout){
var id=window.setInterval(callback, delay);
window.setTimeout(function(){
window.clearInterval(id);
}, timeout);
}
You can use setTimeout and a for loop.
var numberOfTimes = 20;
delay = 1000;
for (let i = 0; i < numberOfTimes; i++) {
setTimeout( doSomething, delay * i);
}
This will clear the interval after 10 calls
<html>
<body>
<input type="text" id="clock" />
<script language=javascript>
var numOfCalls = 0;
var int=self.setInterval("clock()",1000);
function clock()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("clock").value=t;
numOfCalls++;
if(numOfCalls == 10)
window.clearInterval(int);
}
</script>
</form>
</body>
</html>
I made a small package that does this for NodeJS.
https://www.npmjs.com/package/count-interval
It's a drop-in replacement for setInterval (including parameter passing), but it takes an additional count parameter. This example prints a message once every second, but only 3 times.
const countInterval = require('./countInterval');
const timer = countInterval(() => {
console.log('fired!', new Date());
}, 1000, 3);
And for those of you preferring setTimeout and loving recursion here is my suggestion ;)
const setIntervalX = (fn, delay, times) => {
if(!times) return
setTimeout(() => {
fn()
setIntervalX(fn, delay, times-1)
}, delay)
}
Then as suggested you can call the new setInvervalX() function as follows:
// This will be repeated every for 5 times with 1 second intervals:
setIntervalX(function () {
// Your logic here
}, 1000, 5);
You can do this actually very simply with setTimeout() and an incremental counter.
var i = 0; // counter for the timer
function doSomething() {
console.log("1 second"); // your actual code here, alternatively call an other function here
if (++i < 10)
{ // only reset the timer when maximum of 10 times it is fired
console.log("reset the timer");
setTimeout(doSomething, 1000); // reset the timer
}
}
setTimeout(doSomething, 1000); // init the first
This answer is based on SO: Repeating setTimeout and a nice, neat and tidy small combination with this.
You can use Six
SetIntervalX: Limit the number of times that setInterval will fire
import { setIntervalX } from "https://deno.land/x/six/mod.ts";
import { randomNumber } from "https://deno.land/x/random_number/mod.ts";
const API_URL = "https://leap.deno.dev";
async function checkAPIStatus() {
const startTime = performance.now();
const randomYear = randomNumber({ min: 2000, max: 10_000 });
const response = await fetch(`${API_URL}/${randomYear}`);
const data = await response.json();
console.log(`Is ${randomYear} a leap year? ${data.leapYear}.`);
const entTime = performance.now();
console.log(`Request took ${(entTime - startTime) / 1000} seconds.`);
}
setIntervalX(checkAPIStatus, 2000, 15);
Web Page: https://ulti.js.org/six
Repository: https://github.com/UltiRequiem/six
It includes documentation, 100% code coverage, and examples!
Works on Deno, Node.js and the browser!

Categories

Resources