setInterval only runs once with subscription.on - javascript

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);

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.

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.

setTimeout blocking issue

I'm writing a "Game of Life" in javascript. I have all the logic done in a function called doGeneration(). I can repeatedly call this from the console and everything goes as planned, however, if I put it in a while loop the execution blocks the UI and I just see the end result (eventually).
while (existence) {
doGeneration();
}
If I add a setTimeout(), even with a generation limit of say 15, the browser actually crashes (Canary, Chrome).
while (existence) {
setTimeout(function() {
doGeneration();
},100);
}
How can I call doGeneration() once every second or so without blocking the DOM/UI?
You want setInterval
var intervalId = setInterval(function() {
doGeneration();
}, 1000);
// call this to stop it
clearInterval(intervalId);
I would use requestAnimationFrame(doGeneration). The idea of this function is to let the browser decide at what interval the game logic or animation is executed. This comes with potential benefits.
https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/
Rather than using setINterval or setTimeout and assume some random time interval will be enough for the UI to update you shoul/could make the doGeneration smart enough to call itself after dom was updated and if the condition of existence is satisfied.

HTML/JavaScript: How to run a loop while running other code?

I want to have code that simply will count up by one every second or so. However, I also want to be able to run other code alongside it.
Example:
while(true){
Number + 1 + OtherNumber = Number
}
And also be able to run this at the same time:
function onButtonPress() {
OtherNumber++
}
Note: I do not want to increment otherNumber at an interval, but rather on the press of a button.
You can use setInterval:
var intervalId = setInterval(function() {
OtherNumber++;
}, 1000);
It will increase OtherNumber by one approximately every second.
setInterval returns ID of interval, which can be used to stop it:
clearInterval(intervalId);
Demo snippet:
document.body.innerHTML += "Start<br/>";
setInterval(function() {
document.body.innerHTML += "Interval step<br/>";
}, 1000);
document.body.innerHTML += "Look! Code is completed before interval step<br/>";
If you want to run code as two separate threads you will have to use web Workers as Javascript is single threaded and can not run more than one function at a time.
If you create a function
function workForever(){
while(true){
.. do work
}
}
You will completely block all code, no events will get called, no other javascript will be executed. Most browsers will throw up a dialog reporting that a function is taking a long time do you want to kill the page. But your code is stuck in that loop and can only be exited from within the loop itself.
WebWorkers are a good solution to multitasking in the Javascript environment, but you still need to provide some non execution time to allow the webworkers to communicate. The while(true) will block all communication with the workers, in effect making them useless.
SetInterval, setTimeout, requestAnimationFrame will also be blocked. Javascript unfortunately is single threaded and will never be able to run two functions at the same time.

java script for grease monkey loop

what i need is a for or while loop that will re run the code every second
ive tried sleep() but i dont think it is working or i have got it right
Do not try to use a for or while loop for such timed operations. You'll have a hard time with reliable or accurate timing and usually end up railing the CPU, making the computer sluggish.
JavaScript provides the setInterval() function for these kinds of tasks. Also note that Greasemonkey has some caveats about how to use setInterval() and setTimeout().
So the code you want is like:
var timerVar = setInterval (function() {DoMeEverySecond (); }, 1000);
function DoMeEverySecond ()
{
//--- Your code here.
}
//--- When ready to stop the timer, run this code:
clearInterval (timerVar);
timerVar = "";
try
// where yourfunction is a method that contains your loop logic
setTimeout(yourfunction, 1000);
This will invoke the function every 1000 milliseconds without having to embed it into a while or for loop.
put it into your body onload or similar event

Categories

Resources