How do I call a function multiple times 1 second after the same function was executed in the previous call? (JavaScript)
My question is, how can I call the changeArray function after one second? I want the first "changeArray" to be called after 1 second, the next after 2 seconds, and so on. Therefore, each function should be called 1 second after the previous one was executed.
var array = [
[0,0,0],
[0,0,0],
[0,0,0]
];
function changeArray(i,j) {
array[i][j] +=1;
}
changeArray(1,1); //after 1 second
changeArray(1,1); //after 2 seconds
changeArray(0,0); //after 3 seconds
changeArray(0,0); //after 4 seconds
console.log(array);
+3
source to share
4 answers
If there is no rule about how you decide which parameters to pass to changeArray
, you can try the following:
function addInterval(func, i) {
window.setTimeout(function() {
func();
}, 1000 * i);
}
addInterval(() => changeArray(1, 1), 1);
addInterval(() => changeArray(1, 1), 2);
addInterval(() => changeArray(0, 0), 3);
addInterval(() => changeArray(0, 0), 4);
+1
source to share
You can use Window setTimeout
. If you want better syntax or use it inside a loop, you can define a helper method below:
defer = function(method, seconds, args) {
var fn = function() {
return method.apply(null, args);
}
return setTimeout(fn, seconds * 1000);
}
And use it like this:
defer(changeArray, 1, [1, 1]);
defer(changeArray, 2, [1, 1]);
defer(changeArray, 3, [0, 0]);
defer(changeArray, 4, [0, 0]);
Or in a for loop:
var count = 1;
for(var i = 0; i < array.length; i++) {
var row = array[i];
for(var j = 0; j < row.length; j++) {
defer(changeArray, count, i, j);
count++;
}
}
+1
source to share
Departure setTimeout
and setInterval
:
setTimeout(() => changeArray(1,1), 1000); //after 1 second
0
source to share
var counter=0
setInterval(function(){
++window.counter;
var a, b;
if (window.counter== /*however many seconds */ ) {
a=//what ever you want for the time passed
b=//what ever you want for the time passed
}
// add more if statements like that for different times
changeArray(a, b);
}, 1000)
0
source to share