I was trying to make a function, which compares 2 dates, run every 100ms. Since it is kinda bad to run it in the same thread, i wanted to make it run in a second thread so i can do other stuff at the same time. I am using node v16.7.0 btw.
function dateCompare(d1, d2){
if(d1 <= d2){
// Do some json config editing, already got that down dont worry
}
}
I want to make this function run aside of the other code that i have below that (its listening for events if you are curious).
Thanks in advance!
setInterval doesn't block the main JS thread while waiting, nor does setTimeout
Related
Good morning,
I would like to wait for a message (logged to my browser's console by a script I imported in my HTML tag) to be logged and then do an action in JavaScript.
For example, I'd like to wait for "ABCD:READY" to be printed in the console to use a function called finallyStart().
Is it possible ?
I thought I only needed to read the content of stdout to do this, but it looks like browsers don't call their console output stdout...
I also tried to find an answer in stackoverflow, but none of the posts I found were similar to the one I'm currently writing.
I'm a novice when it comes to JS in browsers (I've only used NodeJS for back-end), so thanks in advance for your help !
I faced the same problem and eventually came up with this hacky but working solution.
First create a dummy element in your html.
<div hidden id="start"></div>
Make an event for that element call a function in your js script.
document.getElementById("start").onclick = main;
Then trigger that event manually from your python script.
from pyscript import Element
Element("start").element.click()
No python code can execute until pyscript has finished initializing, so this seems like a reliable strategy. It would be even better if you could call the main() function directly from your python script, but i didn't have the patience to figure that out.
p.s. For some reason it takes a few seconds after pyscript has officially initialized for the code to kick off (at least in my test). I have no idea what's happening during that time, though i suppose it doesn't make a big difference to the already hefty build time.
I have two programs that should be running the same . They are not. I'd like to see where their execution diverges. Is there an option in Chrome or Firefox or Safari to log/echo every line of JavaScript as it is executed ? Or some other way to do this short of manually adding console.log every few lines? Note: the divergence is 10k or 20k maybe 100k lines deep and ideally I'd want it to print variables similar to the Chrome dev tools.
Then I can just dump the logs and find the divergence
Stepping through the code in the debugger is not a solution as it would take hours if not days to step that far.
One idea is to use a babel or uglify plugin to use the last to emit code for each line to print what it is about to do or just did.
Another idea is if there is a way to dump all of memory from js so I can compare all objects and all references. They should be the same so when I see two dumps that differ I'll have found my bug. note: JSON.stringify is not an option as I need to see all variables/objects/classes etc.
Note: I'm not looking for basic answers like "use console.log" or "step in the debugger". I appreciate the help and maybe I've overlooked something simple but I do have quite a bit of JavaScript experience.
Maybe an example would help. Imagine you got the source to an app as large as google docs. You run some processor over it that's not supposed to break anything or change anything. Except it does. You look at the changes and can't see anything wrong. All you know is when you run it it runs but a few things are subtly broken. So you put a breakpoint there and see the data is bad. But when did it go bad? You don't know the code (you just got it). It could have been 100s of thousands of lines before. You have no idea where to put breakpoints or console.logs. It could take weeks. But, given you know the code should run exactly the same if you could print all lines of execution you'd find the bug in minutes instead of days.
You can add debugger; at the begin of the function() or where you want and open the console.
When the debugger is reached it stop the execution. After that you can execute code step by step and add some watches.
It works fine with all recent browser.
Example :
function test()
{
var rand = Math.random();
debugger;
return rand;
}
test();
It is node js but it may be helpful for you. set the NODE_V8_COVERAGE environment variable to a directory, coverage data will be output to that directory when the program exits.
https://blog.npmjs.org/post/178487845610/rethinking-javascript-test-coverage
I have a little snippet of node.js code in front of me that looks like this:
console.time("queryTime");
doAsyncIOBoundThing(function(err, results) {
console.timeEnd("queryTime");
// Process the results...
});
And of course when I run this on my (otherwise idle) development system, I get a nice console message like this:
queryTime: 564ms
However, if I put this into production, won't there likely be several async calls in progress simultaneously, and each of them will overwrite the previous timer? Or does node have some sort of magical execution context that gives each "thread of execution" a separate console timer namespace?
Just use unique labels and it will be safe. That's why you use a label, to uniquely identify the start time.
As long as you don't accidentally use a label twice everything will work exactly as intended. Also note that node has usually only one thread of execution.
Wouldn't this simple code work?
var labelWithTime = "label " + Date.now();
console.time(labelWithTime);
// Do something
console.timeEnd(labelWithTime);
Consider new NodeJS features as it has evolved too. Please look into:
process.hrtime() & NodeJS's other performance API hooks:
https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_timing_api
I'm using the jQuery document ready method - $(function()
If the page takes too long to render (say 2mins+), will this be the reason for the page throwing a javascript taking too long to execute error/warning?
No. $(function(){}) will get called once the DOM is loaded - i.e. it doesn't keep running throughout the load process. Unless you are trying to do a long running synchronous task or stuck in a long loop, you shouldn't get that error.
Have a look at the CPU utilization. If it's high for the browser, it's a tell tale sign that there is an infinite loop somewhere.
depends what you mean by "render".
if you are doing some intense processing in JS (like calculating the millionth prime number or something), the browser will display that message. if you are waiting for a resource to load and aren't grinding away on some script, you will be ok.
No the document.ready only loads after the DOM is ready (i.e after the jquery core is loaded and ready to be used), so it will not throw any error, if a page takes 2-3 mins.
It shouldn't - but test it.
To find out a little more, why not comment out your current load function, and put in a really simple load function, something like:
$(document).ready(function() { alert("load firing");}
See if that makes a difference. Add stuff back in until it breaks.
I am creating a really big JavaScript object on page load. I am getting no error on firefox but on Internet Explorer I am getting an error saying:
Stop running this script ?
A script on this page is causing your web browser to run slowly. If it continues to run, your computer might become unresponsive.
Is there any size limit for Javascript objects in Internet Explorer ? Any other solutions but not dividing the object?
The key to the message your receiving is the "run slowly" part, which relates to time. So, your issue is not object size, but the time taken to construct the object.
To refine things even further, the issue is not the time taken to construct the object either. Rather, IE counts the number of javascript statements it executes, resetting this count when it executes an event handler or a setTimeout function.
So, you can prevent this problem by splitting your code into multiple pieces that run inside calls to setTimeout(...);
Here's an example that may push you in the right direction:
var finish = function(data) {
// Do something with the data after it's been created
};
var data = [];
var index = 0;
var loop;
loop = function() {
if (++index < 1000000) {
data[index] = index;
setTimeout(loop, 0);
} else {
setTimeout(function(){ finish(data); }, 0);
}
}
setTimeout(loop, 0);
The resources available to JavaScript are limited by the resources on the client computer.
It seems that your script is using too much processing time while creating that object, and the 'stop script' mechanism is kicking in to save your browser from hanging.
The reason why this happens on Internet Explorer and not on Firefox is probably because the JavaScript engine in Firefox is more efficient, so it does not exceed the threshold for the 'stop script' to get triggered.
that is not because of the size but because of the big quantity of loops you are executing and the big execution time. if you cut it into smaller parts it should work ok.
Try lowering the complexity of functions your running. Can you post it so that we can look at the loops and try to help?
Edit:
I supose you want to do all that on the client side for some reason. The code seems to need to much execution to be runing on the client side.
Can't you do the calculations on the server side? If this is all to initialize the object, you can cache it to avoid reprocessing and just send a generated json to the javascript side.
It does seem cachable
You must be using big loops or some recursive logic in the code. It really doesn't depend on the size of the object—it depends on the CPU resources it uses (memory, processor, etc.).