I´m trying to execute an http get request to an api every 5 seconds from my reactjs app, although using the setTimeout function, after the first 5 seconds all the requests are done.
getPerson = (url) => {
axios.get(url)
.then(response => {
let person = {};
person.id = response.data.id;
person.name = response.data.name;
person.type = response.data.type;
this.state.persons.push(person);
this.setState({ persons: this.state.persons });
});
}
componentDidMount() {
for(var i = 1; i < 11; i++){
this.getPerson(this.apiUrl + i);
setTimeout(function () {
console.log("waiting for the next call.");
}, 5000);
}
}
componentDidMount() {
let i = 0;
let interval = setInterval(() => {
if (i<11) {
this.getPerson(this.apiUrl + i);
i++;
console.log("waiting for the next call.");
}
else {
clearInterval(interval)
}
}, 5000);
}
You should use setInterval() for that purpose, not setTimeout()
EDIT: In case you somehow don't have access to this in setInterval(), even though you should because it's an arrow function, you can use a workaround
let that = this and then call your method with that.getPerson(that.apiUrl + i);
Still having the problem to access "this" object from inside anonymous block function.
getPerson = (url) => {
axios.get(url)
.then(response => {
let person = {};
person.id = response.data.id;
person.name = response.data.name;
this.state.loadedPersons.push(person);
this.setState({ loadedPersons: this.state.loadedPersons });
});}
componentDidMount() {
for (var j = 1; j < 152; j++) {
this.getPerson(this.apiUrl + j);
}
let i = 1;
let that = this.state;
console.log("That out of in interval:" + that);
let interval = setInterval(function (that) {
console.log("That in interval:" + that);
if ((i<152))
that.persons.push(that.loadedPersons[i]);
i++;
}
else {
clearInterval(interval)
}
}, 5000);
}
Console output:
That out of interval: [Object object]
That in interval: undefined
Related
I am trying to access to intervalId "useState" variable inside of a timeInterval function. But the scope is not working properly. intervalId is always null inside ot the timeInterval function, that means that it does not about delay of value assignation.
export function useLocalCommands(length, id) {
const [intervalId, setIntervalId] = useState(null)
const [currentIndex, setCurrentIndex] = useState(10)
const [timeInterval, setTimeInterval] = useState(Constants.READING.READING_TIME_INTERVAL)
let pauseReading = () => {
console.log("pause:" + intervalId)
clearInterval(intervalId)
}
let startReading = () => {
console.log("play")
pauseReading()
if (currentIndex < length) {
setIntervalId(setInterval(() => {
setCurrentIndex((index) => {
if (index < length) {
if (id && index % 40 === 0) {
Meteor.call('myBooks.updateIndex', id, index, (err, res) => {
// show a toast if err
})
}
return index + 1
} else {
console.log("pauseReading: " + intervalId)
pauseReading();
}
})
}, timeInterval))
}
}
}
Thanks you,
Best.
IntervalId is being used from closure which is why when the setInterval runs, the values being takes at the time of declaration. However setIntervalId triggeres a state update and even though the value of state is updated, your timerId within setInterval function continues to point to the old state that it used from closure.
Instead of using state, you can make use of useRef to store the timerId. Since refs are mutated, they aren't affected by closure
export function useLocalCommands(length, id) {
const intervalId = useRef(null)
const [currentIndex, setCurrentIndex] = useState(10)
const [timeInterval, setTimeInterval] = useState(Constants.READING.READING_TIME_INTERVAL)
let pauseReading = () => {
console.log("pause:" + intervalId.current)
clearInterval(intervalId.current)
}
let startReading = () => {
console.log("play")
pauseReading()
if (currentIndex < length) {
intervalId.current = setInterval(() => {
setCurrentIndex((index) => {
if (index < length) {
if (id && index % 40 === 0) {
Meteor.call('myBooks.updateIndex', id, index, (err, res) => {
// show a toast if err
})
}
return index + 1
} else {
console.log("pauseReading: " + intervalId.current)
pauseReading();
}
})
}, timeInterval);
}
}
}
I am trying to implement two classes that can deal with asynchronous tasks in JavaScript:
Class Task: mimics the execution of a task with setTimeout. Once the timer expires, the task is considered completed.
Class TaskManager: has a capacity parameter to limit the numbers of tasks that can be executing in parallel.
I thought if I could just call the loop function recursively, just to keep checking if one job is done, I could proceed to the next job. But this leads immediately to a "Maximum call stack size exceeded" error.
Can someone explain how I can fix this?
class Task {
constructor(time) {
this.time = time;
this.running = 0;
}
run(limit, jobs, index) {
setTimeout(() => {
console.log('hello', index);
this.done(limit, jobs, index);
}, this.time);
}
done(limit, jobs, index) {
jobs.splice(index, 1);
console.log(jobs);
}
}
class TaskManager {
constructor(capacity) {
this.capacity = capacity;
this.jobs = [];
this.index = 0;
this.running = 0;
this.pending = [];
}
push(tk) {
this.jobs.push(tk);
this.index += 1;
const loop = () => {
if (this.jobs.length === 0) {
return;
}
if (this.jobs.length <= this.capacity) {
this.running += 1;
tk.run(this.capacity, this.jobs, this.index-1);
return;
}
loop();
}
loop();
}
}
const task = new Task(100);
const task1 = new Task(200);
const task2 = new Task(400);
const task3 = new Task(5000);
const task4 = new Task(6000);
const manager = new TaskManager(3);
manager.push(task);
manager.push(task1);
manager.push(task2);
manager.push(task3);
manager.push(task4);
You should not implement the busy loop, as that will block the event loop and so no user UI events or setTimeout events will be processed.
Instead respond to asynchronous events.
If you let the setTimeout callback resolve a Promise, it is not so hard to do.
I modified your script quite drastically. Here is the result:
class Task {
constructor(id, time) {
this.id = id;
this.time = time;
}
run() {
console.log(this + ' launched.');
return new Promise(resolve => {
setTimeout(() => {
console.log(this + ' completed.');
resolve();
}, this.time);
});
}
toString() {
return `Task ${this.id}[${this.time}ms]`;
}
}
class TaskManager {
constructor(capacity) {
this.capacity = capacity;
this.waiting = [];
this.running = [];
}
push(tk) {
this.waiting.push(tk);
if (this.running.length < this.capacity) {
this.next();
} else {
console.log(tk + ' put on hold.');
}
}
next() {
const task = this.waiting.shift();
if (!task) {
if (!this.running.length) {
console.log("All done.");
}
return; // No new tasks
}
this.running.push(task);
const runningTask = task.run();
console.log("Currently running: " + this.running);
runningTask.then(() => {
this.running = this.running.filter(t => t !== task);
console.log("Currently running: " + this.running);
this.next();
});
}
}
const a = new Task('A', 100);
const b = new Task('B', 200);
const c = new Task('C', 400);
const d = new Task('D', 5000);
const e = new Task('E', 6000);
const manager = new TaskManager(3);
manager.push(a);
manager.push(b);
manager.push(c);
manager.push(d);
manager.push(e);
In the following piece of code I try to demonstrate how concatMap preserves the order of events, even if the action performed on events do not complete in order.
Now I get the error that
delayerObservable.complete() is not a function
This basically is just taken from a tutorial. I call next(), and then I call complete(). It should work, at least that's what I thought.
I can achive the desired functionality by returning randomDelayer.first()
return randomDelayer.first()
but I would like to complete the observable from within, since I might want to send out more events than just one.
const myTimer = Rx.Observable.create((observer) => {
let counter = 0;
setInterval( () => {
observer.next(counter++);
console.log('called next with counter: '+ counter);
},2000);
});
const myRandomDelayer = myTimer.concatMap( (value) => {
const randomDelayer = Rx.Observable.create( (delayerObservable) => {
const delay = Math.floor(Math.random()*1000);
setTimeout(() => {
console.log(delayerObservable);
delayerObservable.next('Hello, I am Number ' + value + ' and this was my delay: ' + delay);
delayerObservable.complete(); // <<-- this does not work (not a function)
}, delay);
});
return randomDelayer;
});
myRandomDelayer.subscribe( (message) => {
console.log(message);
});
It seems that there are quite a few changes between version 4 and 6 of the rxjs-framework. The working version of the defective source is this:
const { Observable } = rxjs;
const { map, filter, concatMap, pipe } = rxjs.operators;
console.log('Starting....');
const myTimer = Observable.create((observer) => {
let counter = 0;
setInterval( () => {
counter++;
if (counter < 10){
console.log('nexting now with counter ' + counter);
observer.next(counter);
} else {
observer.complete();
}
},1000);
});
const myRandomDelayer = myTimer.pipe(
concatMap( (value) => {
const randomDelayer = Observable.create( (delayerObservable) => {
const delay = Math.floor(Math.random()*5000);
setTimeout(() => {
delayerObservable.next('Hello, I am Number ' + value + ' and this was my delay: ' + delay);
delayerObservable.complete();
}, delay);
});
return randomDelayer;
})
);
myRandomDelayer.subscribe( (message) => {
console.log(message);
});
for (var i = 0; i <= 5000; i++) {
if(i % 5 == 0){
setTimeout(function() {
console.log(i);
}, 5000);
}
else{
console.log(i);
}
}
I want that once it reaches to number 5 then wait 5 seconds before displaying number 6 in the console. How can I achieve this?
I hope You meant this:
it console.log's non divideable to 5 numbers and then waits 5 second and goes again.
const wait = ms => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
const URL = [...Array(5000).keys()].map(n => n * 2);
const serial = [...Array(5000).keys()].map(n => n * 10);
(async (URL, serial) => {
for (let i = 1; i <= 5000; i++) {
if (i % 5 === 0) {
await wait(5000);
const url = 'http://localhost:3000/?URL='+URL[i]+'&serial='+serial[i];
console.log('Opening url:', url);
window.open(url, '_blank');
continue;
}
await wait(500);
console.log(i);
}
})(URL, serial);
javascript is single thread, try not using blocking as it will freeze your entire program.
SetTimeout and recursion can do the job for you
function print(i,total) {
if (i >= total) {
return;
}
else if (i % 5 === 0) {
setTimeout(function(){
console.log(i);
return print(i+1,total);
},5000)
} else {
console.log(i);
return print(i+1, total);
}
}
print(1,100)
function st(i1) {
setTimeout(function () {
console.log(i1)
},5000)
}
function aa(st) {
return new Promise((resolve => {
for(var i=1;i<=10;i++){
if(i==5){
console.log(i)
i=i+1;
resolve(st(i))
break;
}
console.log(i)
}
}))
}
async function bb() {
var ss=await aa(st)
}
bb()
I have a simple class below that starts and then updates a count every second. How would I go about adding functionality for it to listen for a specific value and then fire a callback?
function Counter() {
this.currentCount = 0;
}
Counter.prototype.start = function() {
setInterval(this.update, 1000);
};
Counter.prototype.when = function(value, callback) {
callback(value);
};
Counter.prototype.update = function() {
this.currentCount++;
};
In my mind it would work something like this.
var counter = new Counter();
counter.when(50, function(value) {
console.log('We arrived at ' + value + ', the requested value.');
});
counter.start();
This is just a nice homework, I'll do that for you ;) Please have a look on my solution:
function Counter() {
this.currentCount = 0;
this.conditions = [];
this.interval = undefined;
}
Counter.prototype.start = function() {
if (!this.interval) {
var that = this;
this.interval = setInterval(function () {
that.update();
}, 1000);
}
};
Counter.prototype.stop = function () {
if (this.interval) {
clearInterval(this.interval);
this.interval = undefined;
}
this.currentCount = 0;
};
Counter.prototype.when = function(value, callback) {
var that = this;
this.conditions.push(function () {
if (that.currentCount === value) {
callback.call(that, value);
}
});
};
Counter.prototype.update = function() {
this.currentCount++;
for (var i = 0, l = this.conditions.length; i < l; i++) {
var condition = this.conditions[i];
condition();
}
};
var counter = new Counter();
counter.when(50, function(value) {
console.log('We arrived at ' + value + ', the requested value.');
});
counter.when(60, function (value) {
console.log('Stop at ' + value + '!');
this.stop();
});
counter.start();
and it's fiddled!
Another answer here made a good argument in hiding private variables, but implemented it a bit too confused, so this is another way of doing it similar. Instead of shared prototype functions this is using instance functions. Some may say this needs more memory, but I don't believe it's significant, and allows to easily have privates in a real constructor function.
var Counter = function () {
var that = this, currentCount = 0,
conditions = [], interval;
var update = function () {
currentCount++;
for (var i = 0, l = conditions.length; i < l; i++) {
var condition = conditions[i];
condition();
}
};
this.start = function () {
if (!interval) {
interval = setInterval(function() {
update.call(that);
}, 1000);
}
};
this.when = function (value, callback) {
conditions.push(function () {
if (currentCount === value) {
callback.call(that, value);
}
});
};
this.stop = function () {
if (interval) {
clearInterval(interval);
interval = undefined;
}
currentCount = 0;
};
};
var counter = new Counter();
counter.when(50, function(value) {
console.log('We arrived at ' + value + ', the requested value.');
});
counter.when(60, function (value) {
console.log('Stop at ' + value + '!');
this.stop();
});
counter.start();
see it fiddled!
Notice also that in both examples, counter is instanceof Counter and Object,
whereas Counter is instanceof Function and Object (why I like to write so much code ;))
To support multiple whens:
Add an array of whens in your class:
function Counter() {
this.currentCount = 0;
this.whens = [];
}
Then let the when function push to that:
Counter.prototype.when = function(value, callback) {
this.whens.push({'time' : value, 'callback' : callback});
}
And check for these whens at update:
Counter.prototype.update = function() {
this.currentCount++;
for(var w in this.whens) {
if(this.currentCount == this.whens[w].time) {
this.whens[w].callback();
}
}
}
Try something more like:
function Counter(interval, val, func){
this.currentCount = 0;
setInterval(function(){
this.currentCount++;
if(this.currentCount === val)func();
}, interval);
}
var nc = new Counter(1000, 50, function(){
console.log('We have arrived at '+nc.currrentCount);
});
There is an argument to be made for something like this instead:
var Counter = (function() {
var update = function() {
var idx, callbacks;
this.currentCount++;
callbacks = this.callbacks[this.currentCount];
if (callbacks) {
for (idx = 0; idx < callbacks.length; idx++) {
callbacks[idx](this.currentCount);
}
}
};
var start = function() {
var counter = this;
setInterval(function() {update.call(counter)}, 1000);
};
var when = function(count, callback) {
(this.callbacks[count] || (this.callbacks[count] = [])).push(callback);
};
return function() {
var config = {currentCount: 0, callbacks: {}};
this.start = function() {return start.call(config);};
this.when = function(count, callback) {
return when.call(config, count, callback);
};
// this.stop = ... // if desired
};
}());
This is somewhat more memory intensive than the prototype-based version of the code. I wouldn't use it for something where you were expecting hundreds of thousands or millions of objects. But it has the advantage that it truly encapsulates the data you might like to keep hidden, such as currentCount and the list of callbacks. It doesn't expose an unnecessary update function. And it's not terribly more heavy than the prototype version. Each instance has its own start and when functions, but those are just thin wrappers around common functions.
It is a bit more difficult to add a stop function to this in the same manner, unless you don't mind exposing the the result of setInterval. But it is doable.