Javascript - telling setInterval to only fire x amount of times?
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);
How to run a function a certain number of times with a specific time interval
Try this:
let count = 0;
const test = () => {
let positionsArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(
positionsArray[Math.floor(Math.random() * positionsArray.length + 0)]
);
if(++count === 5) clearInterval(interval);
};
const interval = setInterval(test, 2000);
How can i get counter from setInterval?
Here is an example:
it works every one second in order to do the countdown but once it reach to the 60 it resets the countdown and does the request.
const timer = document.querySelector('#timer');
let counter = 60;
setInterval(() => {
if (counter === 0) {
//this.takeTableDataCallInterval();
counter = 60;
}
else {
timer.innerHTML = `${counter} seconds left`;
counter--;
}
}, 1000);
<p id="timer"></p>
perform function after x number of calls with setInterval
function setIntervalX(func, delay, times, callback) {
if (times > 0) {
setTimeout(function() {
func.apply(arguments.callee);
setIntervalX(func, delay, --times, callback);
}, delay);
} else {
callback.apply(this);
}
}
setIntervalX(function() {
document.write('ping!<br />');
}, 1000, 5, function() {
document.write('Finished!<br />');
});
I personally prefer the setTimeout method... but that is just me. give this a shot and see if it works. demo
Ahh it appears I have misread you're entire post... so Tobias is correct in his reasoning for your question. mine is an example of what you want.
setInterval/setTimeout problem getting messages at once
You need to give the CPU a breather
let amount = 5;
const interval = 300; // 3000
const tId = setInterval(() => {
console.log(amount)
// message.channel.send($arr[Random(0, $arr.length)]);
if (--amount === 0) clearTimeout(tId);
}, interval);
Changing the interval of SetInterval while it's running
Use setTimeout()
instead. The callback would then be responsible for firing the next timeout, at which point you can increase or otherwise manipulate the timing.
EDIT
Here's a generic function you can use to apply a "decelerating" timeout for ANY function call.
function setDeceleratingTimeout(callback, factor, times)
{
var internalCallback = function(tick, counter) {
return function() {
if (--tick >= 0) {
window.setTimeout(internalCallback, ++counter * factor);
callback();
}
}
}(times, 0);
window.setTimeout(internalCallback, factor);
};
// console.log() requires firebug
setDeceleratingTimeout(function(){ console.log('hi'); }, 10, 10);
setDeceleratingTimeout(function(){ console.log('bye'); }, 100, 10);
Timing in JS - multiple setIntervals running at once and starting at the same time?
Good question, but in JS you can't. To have multiple functions in the same program execute at the same time you need multi-threading and some deep timing and thread handling skills. JS is single threaded. setInterval
doesn't acutally run the function after the delay, rather after the delay it adds the function to the event stack to be run as soon as the processor can get to it. If the proc is busy with another operation, it will take longer than the delay period to actually run. Multiple intervals/timeouts are all adding calls to the same event stack, so they run in turn as the proc is available.
setInterval slugish in IE 8 at 50 times a second
New discovery: Internet Explorer sucks.
Well, at least IE8 and older. IE9 has fine performances.
The problem with timed functions triggered by setTimeout
and setInterval
is that the browser attempts to execute the functions when the time is due, but this actually happens only if it's idle. And since Internet Eplorer <9 is so slow, and is always "late" for something, you can understand why that animation isn't good.
The problem is that everytime you execute a "frame", IE8 takes more than 50 milliseconds to accomplish all the tasks caused by calculations and DOM changes.
Related Topics
How to Create an Auto-Complete Combobox
Create File with Google Drive API V3 (Javascript)
What Are Some Empirical Technical Reasons Not to Use Jquery
React Doesn't Reload Component Data on Route Param Change or Query Change
What Is Event Pooling in React
How to Pass a Flag to Gulp to Have It Run Tasks in Different Ways
Differencebetween Native Objects and Host Objects
JavaScript String and Number Conversion
Click Everywhere But Here Event
Access 'Data-' Attribute Without Jquery
Access Properties of the Parent with a Handlebars 'Each' Loop
Mocking a Useragent in JavaScript
Remove Whitespace and Line Breaks Between HTML Elements Using Jquery
Unexpected Token Illegal in Webkit
Passing a PHP Variable to JavaScript in a Blade Template
Do Browsers Parse JavaScript on Every Page Load