I have a problem. The values from the data array should be increased or decreased every 5 seconds with 0.0001 by following the rule: values should go up for the first minute, then down for the next minute, and so on -
const data = [
{ AUD: "1.5876" }, { BGN: "1.9558" }, { GBP: "0.8527" }, { USD: "1.1820" },
{ UYU: "51.9732" }, { UZS: "12570.5509" }, { VEF: "252746931045.8590" },
{ VND: "27195.9489" }, { VUV: "130.1601" }, { WST: "3.0161" }, { XAG: "0.0449" },
{ XAU: "0.0006" }, { XCD: "3.1944" }, { XDR: "0.8306" },
];
This is my code, but i got an infinity loop.
const [currencies, setCurrencies] = useState([]);
let initialTime = true;
useEffect(() => {
let init = setTimeout(() => {
initialTime = false;
console.log('changing the time ' + initialTime);
}, 5000);
return () => clearTimeout(init)
}, []);
function increase() {
data.forEach(e => {
let value = Number(Object.values(e)[0]);
const key = Object.keys(e)[0];
setCurrencies({ [key]: value += 0.0001 });
})
console.log(currencies);
}
let interval = setInterval(() => {
if (initialTime) {
increase()
} else {
return () => clearInterval(interval);
}
}, 1000);
So keep track of the time and determine how long it has been and when it hits the length of time, flip it.
let updateTime = Date.now();
const endTime = updateTime + 20000;
let dir = 1;
let value = 1.2357;
const flipTime = 5000;
const timer = setInterval(function () {
if(Date.now() - updateTime >= flipTime) {
updateTime = Date.now();
dir *= -1;
}
value += dir * .0001;
console.log(value.toFixed(4));
// If over end time, stop looping
if (Date.now() >= endTime) {
window.clearTimeout(timer);
}
}, 1000);
Side note, setInterval is not 100% accurate so you will see the numbers float around as time runs on.
Related
export function useTimer(initValue: number, isProceed: boolean) {
const [value, setter] = useState(initValue)
useEffect(() => {
setter(initValue)
const interval = setInterval(() => {
if (isProceed && value > 0) setter((c) => c - 1)
else if (value < 0) {
clearInterval(interval)
}
}, 1000)
return () => {
clearInterval(interval)
}
}, [initValue, value, isProceed])
return {
seconds:
value > 0
? `${Math.floor(value / 60)}:${value % 60 < 10 ? '0' : ''}${value % 60}`
: '',
resetTimer: () => setter(initValue),
}
}
test('InitialCountState < 0', async () => {
const { hydrate, result, waitForValueToChange } = renderHook(() =>
useTimer(InitialCountState, isStartTimer)
)
InitialCountState = -1
isStartTimer = true
hydrate()
await waitForValueToChange(() => result.current.seconds)
expect(result.current.seconds).toBe('')
})
Timed out in waitForValueToChange after 1000ms.
Failed to resolve failure result during hooks test. It's said that it failed because it was over time, but I don't know how to solve it. Is there a good way?
I have a script when using the library typed.js . I'm trying to output 3 lines + 1 final one. The code works by outputting 2 lines + 1 final one. When trying to fix it, the code freezes without sending an error.
This version of the code works without errors. Outputs 2 lines + 1.
const lineNumber = app.id !== 2 ? ++app.id : (app.id += 2);
setTimeout(() => {
const typed = new Typed(`#line${lineNumber}`, {
strings: text,
typeSpeed: speed,
onComplete: callback,
});
}, timeout);
};
$.getJSON(ipgeolocation, (data) => {
writeLine(["line1"], 30, () => {
if (app.skippedIntro) return;
clearCursor();
const usernames = ['user', 'dude'];
const ip = data.ip ? data.ip : usernames[Math.floor(Math.random() * usernames.length)];
const country = data.country_name ? data.country_name : 'your country';
writeLine([`line2`], 30, 500, () => {
if (app.skippedIntro) return;
clearCursor();
writeLine([`start`], 120, 500, () => {
timeouts.push(
setTimeout(() => {
if (app.skippedIntro) return;
clearCursor();
setTimeout(() => {
skipIntro();
}, 500);
}, 1000)
);
});
});
});
});
This version of the code does not work. According to the idea, it should output 3 lines + 1.
1.
const lineNumber = app.id !== 2 ? ++app.id : (app.id += 2);
setTimeout(() => {
const typed = new Typed(`#line${lineNumber}`, {
strings: text,
typeSpeed: speed,
onComplete: callback,
});
}, timeout);
};
$.getJSON(ipgeolocation, (data) => {
writeLine(["line1"], 30, () => {
if (app.skippedIntro) return;
clearCursor();
const usernames = ['user', 'dude'];
const ip = data.ip ? data.ip : usernames[Math.floor(Math.random() * usernames.length)];
const country = data.country_name ? data.country_name : 'your country';
writeLine([`line2`], 30, 500, () => {
if (app.skippedIntro) return;
clearCursor();
writeLine([`line3`], 30, 500, () => {
if (app.skippedIntro) return;
clearCursor();
writeLine([`start`], 120, 500, () => {
timeouts.push(
setTimeout(() => {
if (app.skippedIntro) return;
clearCursor();
setTimeout(() => {
skipIntro();
}, 500);
}, 1000)
);
});
});
});
});
});
We have the main bands and when you get 3, you need to add 2 to learn the 5th.
const lineNumber = app.id !== 3 ? ++app.id : (app.id += 2);
I have the below code in a vue application
mounted: function () {
this.timer = setInterval(async () => {
if (this.progress >= 1) {
this.progress = 1
clearInterval(this.timer)
}
console.log('update')
const id = this.$route.params.id
const progOut = await this.api.get(`/api/mu/job/${id}/status`)
const response = progOut.data
this.progress = response.data.progress / 100
this.state = response.data.status
}, 7000)
},
I was expecting it to execute the get request every 7 seconds but it is executing the call every 500ms approx
I read other answers and so far I think this is the proper way but the code is executing too many requests
What is the proper way to call a function from within the setInterval to make it actually wait the timeout?
Edit: This was my final code in case someone goes through the same
methods: {
redirect (page) {
if (page === 'FINISHED') {
this.$router.push({
name: 'viewReport',
params: { id: 4 }
})
} else {
this.$router.push({
name: 'errorOnReport',
params: { id: 13 }
})
}
}
},
watch: {
state: async function (newVal, old) {
console.log('old ' + old + ' newVal ' + newVal)
if (newVal === 'FAILED' || newVal === 'FINISHED') {
this.redirect(newVal)
}
}
},
data () {
return {
state: null,
timer: null,
progress: 0.0,
progressStr: '0%'
}
},
mounted () {
const update = async () => {
if (this.progress >= 1) {
this.progress = 1
}
console.log('update ' + new Date())
const id = this.$route.params.id
const progOut = await this.api.get(`/api/mu/job/${id}/status`)
const response = progOut.data
this.state = response.data.status
this.progress = response.data.progress / 100
this.progressStr = response.data.progress + '%'
}
update()
this.timer = setInterval(update, 10000)
},
beforeUnmount () {
clearInterval(this.timer)
}
A better design is to wrap setTimeout with a promise, and do the polling in an async method that loops...
mounted: function() {
this.continuePolling = true; // suggestion: we have to stop sometime. consider adding continuePolling to data
this.poll();
},
unmounted: function() { // almost the latest possible stop
this.continuePolling = false;
},
methods:
async poll(interval) {
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
while(this.continuePolling) {
await this.updateProgress();
await delay(7000);
}
},
async updateProgress() {
const id = this.$route.params.id
const progOut = await this.api.get(`/api/mu/job/${id}/status`)
const result = progOut.data.data;
this.progress = result.progress / 100
this.state = result.status
}
I have the following code:
const timers = []
const timer1 = setTimeout(() => {
console.log('Starting timer2')
const timer2 = setTimeout(() => {
console.log('Its works')
}, 10000)
timers.push({key:2, id:timer2})
}, 10000);
timers.push({key:1, id:timer1})
function remove(key) {
for (i = 0; i > timers.length; i++) {
if (timers[i].key === key) {
timers = timers.slice(i, 1)
clearTimeout(timers[i].id)
}
}
}
When I call the remove(key) function the code is not removing the timers as expected
const timers = []
const timer1 = setTimeout(() => {
console.log('Starting timer2')
const timer2 = setTimeout(() => {
console.log('Its works')
}, 10000)
timers.push({key:2, id:timer2})
}, 10000);
timers.push({key:1, id:timer1})
function remove(key) {
const timer = timers.find(f => f.key === key);
if (timer) {
clearTimeout(timer.id);
}
}
I have two .js-files:
main.js
require("./randomEvent.js").start("hey");
require("./randomEvent.js").start("hi");
require("./randomEvent.js").start("hello");
randomEvent.js
var repeat = true;
exports.start = (randomString) => {
while (repeat) {
console.log(randomString);
}
}
exports.stop = (randomString) => {
repeat = false;
}
I want to start randomEvent.js 3 times, each with different randomStrings.
And if I do
require("./randomEvent.js").stop("hi");
it should stop the start("hi") function / it should set repeat to false.
How?
Thanks in advance!
You can implement your randomEvents.js as a class. So every instance has its own repeat flag.
function RandomEvent(str) {
this.repeat = true;
this.randomString = str;
this.start = () => {
setInterval(() => {
if (this.repeat) {
console.log('-->', this.randomString);
}
}, 1000);
}
this.stop = () => {
this.repeat = false;
}
}
module.exports = RandomEvent;
and main.js
let RandomEvent = require('./randomEvent');
let sayHi = new RandomEvent('hi');
let sayHello = new RandomEvent('hello');
let sayHey = new RandomEvent('hey');
sayHi.start();
sayHello.start();
sayHey.start();
setTimeout(() => {
console.log('stop saying hi')
sayHi.stop();
}, 5000);
Or you can store for every string, its own flag:
randomEvents.js
var repeat = {};
exports.start = (randomString) => {
repeat[randomString] = true;
setInterval(() => {
if (repeat[randomString]) {
console.log('-->', randomString);
}
}, 1000);
}
exports.stop = (randomString) => {
repeat[randomString] = false;
}
and in main.js
require("./randomEvent.js").start("hey");
require("./randomEvent.js").start("hi");
require("./randomEvent.js").start("hello");
setTimeout(() => {
console.log('stop saying hi')
require("./randomEvent.js").stop("hi");
}, 5000);
randomEvent.js
var repeatFlags = {};
function repeatLog(str) {
if (repeatFlags[str]) {
console.log(str);
setTimeout(() => {
repeatLog(str);
});
}
}
exports.start = (randomString) => {
repeatFlags[randomString] = true;
repeatLog(randomString);
}
exports.stop = (randomString) => {
repeatFlags[randomString] = false;
}