NodeJS - Async Clear Interval Not Working - javascript

I am having major issues stopping an async interval from continuing.
This starts the infinite interval:
task.interval = setIntervalAsync(
async() => await this.sendTimer(task, savedGuild), interval);
Class that creates the bug:
https://pastebin.com/qq5tReFq
Line that doesn't do anything:
while (task.interval)
clearIntervalAsync(task.interval);
Sorry if this is unhelpful, but I have tried many different types and intervals and when endTimers is called the interval continues as if nothing has happened. Please send help.

const guildTimers = timers.currentTimers.get(req.params.id);
if (!guildTimers || guildTimers?.length <= 0)
return res.json([]);
for (const timer of guildTimers)
delete timer.interval; // <- the cause of the problem
I managed to find the issue. It was found in an external file, on the API, that allows the user to view the scheduled tasks.
delete timer.interval removed the reference to the interval, and therefore stopped it from being reset as timer.interval was undefined.

Related

Lambda function runs for 2 seconds every time but not running the code inside it

I have a Lambda function which is super super basic and it won't run anything inside it. This is pretty much how I start all Lambda functions, as in I handle the event that triggered it and then output 1-2 pieces of data from that event to make sure it works. However when I am doing it now it seems that the function will not run any code. It complete in 2-2.5 seconds every time even if I add a set timeout to 5 seconds. Below is the current iteration of test / setup code. How can I fix this so that it will actually run the function properly and in full?
module.exports.email = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
let input = JSON.parse(event.Records[0].body);
let message = JSON.parse(input.Message)
let companyID = message.companyID
let email = message.email
console.log(companyID)
console.log(email)
return true
}
Edit** Please ignore the settime I guess, it was part of testing if the function would run code or not, I now see it was wrong but that still doesn't explain why the console.log's wouldn't run
Edit 2** Resolved the issue, wasn't a code issue but instead was an AWS one I think since I did a sanity test and it worked with the exact same code that is in the OP here.

SetInterval() and async function? CPU working too hard with TF.js

I have written a code for webcam classification in Tensorflow.js. By combining advice from many tutorials, it now works. However, in its current stage, it's very expensive for the system as the Tensorflow.js. predictions loop with while (true). Google Chrome Helper (renderer) uses 50-60% of the CPU with this code running in the browser.
For me, it would be enough to make the prediction calculations every 0.5-1 seconds if that takes off some of the CPU strain. However, as a beginner I'm still confused how to add setInterval() to my current code (replacing the while(true) loop). I wonder if anyone could point me to right direction? Or if there is any other way to avoid the CPU strain with this code. Many thanks!
async function app() {
const model = await tf.loadGraphModel(MODEL_URL);
console.log('Successfully loaded model');
const labels = ["not_monster", "monster"];
console.log(labels);
const webcam = await tf.data.webcam(video);
while (true) {
tf.engine().startScope();
const img = await webcam.capture();
const smalImg = tf.image.resizeBilinear(img, [224, 224]);
const resized = tf.cast(smalImg, 'float32');
const t4d = tf.tensor4d(Array.from(resized.dataSync()),[1,224,224,3]);
const result = await model.predict(t4d);
result.print();
result.as1D().argMax().print();
const labelIndex = result.as1D().argMax();
const predictionLabel = result.as1D().argMax().dataSync()[0];
const predict = await result.data();
const value = predict[predictionLabel];
document.getElementById("demo").innerHTML = `
Numeric prediction is: ${labelIndex}\n
The predicted label is: ${labels[predictionLabel]}\n
Confidence is: ${value}\n
`;
if (labels[predictionLabel] == "monster"){
var data = {
speed: 100
}
socket.emit("monster", data);
}
else {
socket.emit("not_monster");
}
img.dispose();
result.dispose();
smalImg.dispose();
resized.dispose();
t4d.dispose();
tf.engine().endScope();
await tf.nextFrame();
} // closes loop
} // closes app
requestAnimationFrame(() => this.app());
You already have a setinterval loop:
requestAnimationFrame(() => this.app());
This works exactly like the same as:
setInterval(() => this.app(), 16.66666666667);
(well, almost exactly. It's hard to get exact millisecond value for 1/60 seconds).
So basically your app already have a giant while loop outside in the form of requestAnimationFrame() which you can also replace with setInterval() like I did above if you want to.
This causes this.app() to be called 60 times each second.
So, after one second of execution you will end up with 60 while loops running in the background (thanks to await).
After 10 seconds of execution you will end up with 600 while loops running in the background (waiting for 600 calls to Tensorflow).
After one minute you will be waiting for 3600 parallel calls to Tensorflow.
After 10 minutes that will end up awaiting for 36000 parallel calls to Tensorflow.
No wonder it is taking 60% CPU time. And it will get worse over time.
Before trying to replace requestAnimationFrame() with setInterval() I suggest you delete the while() first. You don't have to remove code inside the while loop just remove the while (true) { and } at the end.
The requestAnimationFrame() will try to call your function 60 times per second (basically acting as a while loop). If you want to run your function every 0.5 seconds instead replace it with:
setInterval(() => this.app(), 500);
To run your function every 1 second you do:
setInterval(() => this.app(), 1000);
Since requestAnimationFrame will run 'app' repeatedly no need to also loop in 'app'
while (true) { ... }

setInterval only runs once with subscription.on

I have a node script that I use to store data from some microsensors and I was writing a setInterval function and noticed that it was only running for the first 3 or so seconds of the script. I was able to isolate the bug to the subscirption.on portion of my script.
const subscription = pubsub.subscription(config2.gcpPubSubSubscriptionName);
subscription.on('message', message => {
storeEvent(message);
message.ack();
});
setInterval works as expected when I remove this. Why is the above piece of code causing setInterval to mess up.
Here's my setInterval
let i =0
async function notificationQueue(){
i++
console.log('setInterval ran '+i)
}
setInterval(notificationQueue, 2000);

How would you terminate an infinite loop (`setInterval`) in the console?

For instance, we could run
setInterval(function(){console.log("Hello, SO!")}, 2000);
Hello, SO! gets repeated every two seconds in the terminal. There are 6 repeats in the picture below.
Is there a key combination you could press or command you could type to stop the infinite loop in the console?
This is your best bet that I know of.
var interval = setInterval(() => console.log("hello, world"), 2000);
clearInterval(interval);
To kill intervals, you need a handle to them to pass to clearInterval(). In your image, after you execute setInterval(), you can see the handle is returned to the console as 4491. In this way, you can kill it like so:
clearInterval(4491);
Alternatively (and better), you should assign that handle return to a variable so you can kill it programmatically:
let interval = setInterval(() => console.log('Hello, SO!'), 2000);
clearInterval(interval);
Edit:
You can also brute-force. The handle is an int64 number, so it could potentially be enormous, but for almost any app, it'll be small since the handles are incremented. Note that this method could break other packages that rely on intervals.
for (var i = 1; i < 9999; i++) clearInterval(i);
You can stop script execution on the current page using the pause button described here. This will pause all JS on the page though, not just your interval.

JavaScript Timer clearInterval complications

So I'm attempting to make a Pomodoro Timer without using an API (I know, stupid choice) but I feel as if I'm over-complicating this issue.
I forked my CodePen so I could post the current code here without confusing anyone. My Code Pen
To see my issue: Just set Timer to .1 and Break to .1 - You'll see the Start to Resume works fine, but the Resume to start has issues.
I built in consoleLogs to track it and I see the Work Timer TRIES to start but then breakTimer over-runs it, and duplicates on every pass.
Why isn't my clearInterval working?
Things I've tried:
Adjusting names of clearInterval,
Setting it so it goes back to startTimer instead of start
force quitting it (instead of looping it back to startInterval.
The function is virtually identical to my startFunction yet fails to work properly. Would appreciate any input (I'm new to clearInterval but I believe I am using it right.)
function breakTimer() {
$('.jumbotron').css('visibility', 'visible');
setInterval(function() {
console.log("Break Timer...");
breakTime--;
if (breakTime < 0) {
clearInterval(timer);
working = false;
start();
} else {
showTime(breakTime);
}
}, 1000);
}
Edit:
To answer the reply:
function start() {
if (working == true){ //This keeps it from being spammable
return;
} //Else
workTime = $('#work').val()*60;
breakTime = $('#break').val()*60;
working = true;
checkStatus();
timer = startTimer();
}
Unsure if I should post every Function here
As per definition, the value returned by setInterval(...) is the ID of the created timer. As such, with your code you can only stop the last created timer because the ID in the timer variable gets overwritten, causing it to lose control over the previously created (and still running) timers.
The ID is what you pass on to clearInterval(...) to stop a timer. You will have to do this in a different way. You may ask for a different way in https://codereview.stackexchange.com/

Categories

Resources