How to stop a function after ten seconds? - javascript

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);
}
})();

Related

How can I postpone setInterval if a condition is met?

This is my script:
var find = setInterval(function() {
if (document.getElementsByClassName('RDlrG Inn9w iWO5td')[0]) {
if (document.getElementsByClassName('w1OTme')[0]) {
window.open(document.getElementsByClassName('w1OTme')[0].href);
//here I call the setTimeout function for my SetInterval
}
}
}, 2000);
This is a Tampermonkey script I am developing for Google Calendar.
I want to set a timeout function on my find function aka setInterval function so it doesn't spam the window.open function.
In short:
Is there a way I could set a Timeout function on setInterval function which is called from my setInterval function?
If yes, how so?
You can't pause the interval of a setInterval, but you can stop it and start it again after some time.
let find = null;
function intervalFunc() {
if (condition) {
// Do some operations which should not be repeated for the next 30 seconds
// Clear current interval
clearInterval(find);
// Schedule to start the setInterval after 30 seconds.
setTimeout(function() {
find = setInterval(intervalFunc, 2000);
}, 30000 - 2000);
// ^
// Subtracting the interval dalay to cancel out the delay for the first invocation.
// (Because the first invocation will also wait for 2 seconds, so the pause would be 32 seconds instead of 30)
}
}
// Start the initial setInterval
find = setInterval(intervalFunc, 2000);
Here is a working example:
let count = 0;
const intervalDelay = 200;
const pauseDelay = 3000;
let find = null;
function intervalFunc() {
count++;
console.log('check', count);
if (count >= 5) {
count = 0;
console.log('Pausing for ' + (pauseDelay / 1000) + ' seconds');
clearInterval(find);
setTimeout(function() {
find = setInterval(intervalFunc, intervalDelay);
}, pauseDelay - intervalDelay);
}
}
find = setInterval(intervalFunc, intervalDelay);

clearInterval stopping setInterval working purely time based

I'm newbie in JS/jQuery, and got quite confused about the usage of stopping a setInterval function from running in x ms (or after running X times), which apparently happens with clearInterval. I know this question was asked similarly before, but couldn't help me.
As you see, it starts with 1000ms delay, and then repeat for 9000ms (or after running 3 times if better??), and then it needs to stop. What's the most ideal way of doing this? I couldn't properly use the clearInterval function. Thanks for the answers!
var elem = $('.someclass');
setTimeout(function() {
setInterval(function() {
elem.fadeOut(1500);
elem.fadeIn(1500);
},3000);
},1000);
To stop the interval you need to keep the handle that setInterval returns:
setTimeout(function() {
var cnt = 0;
var handle = setInterval(function() {
elem.fadeOut(1500);
elem.fadeIn(1500);
if (++cnt == 3) clearInterval(handle);
},3000);
},1000);
Create a counter, and keep a reference to your interval. When the counter hits 3, clear the interval:
var elem = $('.someclass');
setTimeout(function() {
var counter = 0;
var i = setInterval(function() {
elem.fadeOut(1500);
elem.fadeIn(1500);
counter++;
if (counter == 3)
clearInterval(i);
},3000);
},1000);
Given what you are trying to do is quite static, why not simply add delays and forget all the timers.:
var elem = $('.someclass');
elemt.delay(1000).fadeOut(1500).fadeIn(1500).delay(3000).fadeOut(1500).fadeIn(1500).delay(3000).fadeOut(1500).fadeIn(1500).delay(3000);
Or run the above in a small loop if you want to reduce the code size:
elemt.delay(1000);
for (var i = 0; i < 3; i++){
elemt.fadeOut(1500).fadeIn(1500).delay(3000);
}
You just need to clear the interval after three times:
setTimeout(function() {
var times = 0;
var interval = setInterval(function() {
elem.fadeOut(1500);
elem.fadeIn(1500);
if (++times > 3) clearInterval(interval);
},3000);
},1000);

Javascript function, need to decrement every 30 secs time elapsed

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);

Changing a variable value every 5 seconds and return

Why this script does not work correctly (freezes sometimes)?
var period = 600;
function Boom(){
var timeBoom = window.setInterval(function() {
if (period > 300) {
period = 300;
setTimeout(function () {
period = 600;
}, 1000);
} else {
period = 600;
}
}, 5000);
}
function Shake() {
this.draw = function() {
setTimeout(function () {
Boom()
}, 5000)
};
}
I need to just every 5 seconds the function Boom() was called, but the variable should be changed back again after executing (var period = 600).
ok mate, basically you need to get rid of all the un needed timing stuff.
first of all, a brief explanation:
setTimeout (func, x) will execute function func after x milliseconds.
setInterval (func, x) will execute function func Each x milliseconds.
so you only need to set interval one time, and let it work. i have corrected your code:
var period = 600;
function Boom() {
if (period != 300) {
period = 300;
} else {
period = 600;
}
}
function Shake() {
this.draw = function () {
var time = new Date().getTime();
var shakeX = (Math.sin(time * 2.0 * Math.PI / period) + 0);
this.x = shakeX;
var shakeY = (Math.sin(time * 2.0 * Math.PI / period) + 0);
this.y = shakeY;
this.context.drawImage(image, 0, 0);
this.context.translate(this.x, this.y);
setInterval(Boom, 5000)
};
}
John Resig -- creator of jQuery -- has a very nice piece on javascript timers.
Basically, becuse javascript is single-threaded, setInterval is not guaranteed to fire on every interval -- it will miss a beat if the js engine is busy at a particular cycle.
setTimeout will always call, but there could be an extra delay if another piece of code is queued up already when the time expires -- that is, the wait is potentially longer than the number of milliseconds you passed in as the second argument.
I'm guessing some of your setTimeout code might be getting in the way of one of the setInterval loops, but that's just a guess.
If that's the issue, try naming the anonymous fn you passed into setInterval, and then pass it into setTimeout instead, with 5000 ms wait, and another call (recursive) to the same function at when the interval expires.

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