Is my code forking? - javascript

function loopthrough (i) {
i++;
if (i <= 20) {
play_multi_sound("aud"+i);
$("#debug").html(i);
setTimeout("loopthrough("+i+");",242); }
else {
loops++;
$("#debug").html("rest");
$("#loops").html(loops);
setTimeout("loopthrough("+0+");",1000);
}
}
Does my code look like it is forking? since after about 3 loops it is litrally crashing the browser. I am using excessive HTML5 audio since I like to test new features and whilst im still a newbie at Javascript I really need this code to work. (Im making a simple beat game in canvas where you use a pong style paddle and each ball you hit of varying speed it will play a sound, thus making a cool beat)... Atm im just testing the capabilities of alot of audio being looped through at once.
So yeah my basic question is "Is my code efficient, is it forking and is there anyway of improving this greatly if you know of a better way?"
Thanks,
Tom C.
EDIT:
Just removed my loops++; (for some reason it was returning NaN even though it was defined as global) and it actually successfully looped 20 times without flaws.

I just did some tests, and I am sticking it here so that the code is clear.
function loopthrough (i) {
i++;
if (i <= 20) {
console.log("bla");
setTimeout(function(){ loopthrough(i); }, 242); }
else {
console.log("lala");
setTimeout(function(){ loopthrough(0); }, 1000);
}
}
loopthrough(0);
That worked fine and it never crashed. And it didn't fork either.
So, it's crashing on something else.
I would try this in another browser as well, and see if it crashes - could just be the FF beta 8 crashing.
Try removing 1 bit at a time from it and see if it starts to work - it's a good way to narrow down the culprit.
I bet it's the audio that's crashing it...
* update *
Try bumping up the timeout delay - it could be that the audio doesn't finish and then attempts to play again and is somehow backlogging.

Related

Looping audio in midijs?

I'm trying to use MIDIjs to play audio (specifically because I'm using WAD.js, which uses it). Unfortunately I can't figure out how to loop audio, there's a frustrating lack of documentation, and I'm not finding anything in the source code. At the very least I'd like to know when the file has naturally ended to restart using MIDIjs.play(), but I'm not even seeing anything for that.
I'd appreciate it if someone pointed me towards a solution, thank you.
Correct, there's no loop function (that's documented anywhere here).
However, we can at least simulate it with MIDIjs.player_callback, which is called every 100ms with an object that looks like { time : number }. This is time in seconds elapsed. We can combine this with get_duration to detect the end of playback.
function playAutoReset(url)
{
// get_duration requires a callback as it returns nothing.
MIDIjs.get_duration(url, function (duration)
{
console.info(`Duration: ${duration}`);
// Start the initial play
MIDIjs.play(url);
// This lets us keep track of current play time in seconds
MIDIjs.player_callback = function (mes)
{
if (mes.time / duration >= 1)
{
console.info('End reached');
// This plays the audio again
MIDIjs.play(url);
}
};
});
}
Note:
This does call play each time, so it will probably re-download the source (the docs seem to imply that this is always the case). If you want something more network-efficient, you may want to look into XHRs/AJAX and creating an object URL, as the docs do specify that play takes a URL. However, I thought this would be the simplest solution, and it does show what you have to do to play the midi track again when it ends.
I had this same issue and wasn't entirely satisfied with the workaround in the other answer because of how it reloaded the file every time the url was passed into a MIDIjs function and it seemed to loop slightly too early.
So, I started digging into the MIDIjs source, which also has a map file, but I didn't bother trying to maximize/deobfuscate it. I noticed a couple mentions of loop that are set by second parameter t in function X. I wasn't sure, but thought maybe X was play, so I tried it.
MIDIjs.play(url, true);
It worked!
Since I'm working with Kotlin/JS, here's my external code:
external object MIDIjs {
fun play(url: String, loop: Boolean = definedExternally)
fun stop()
}
Call it in Kotlin exactly the same way, without the semicolon.
MIDIjs.play(url, true)

What is the best way to take up as much CPU as possible using javascript?

I am writing a website for one of my friends, and as a joke I want one page to have javascript that uses as much CPU as possible. The javascript doesn't actually have to do anything, just needs to somehow make computers as slow as possible while hes on the page. What is the best way to do this?
Just a simple infinite loop will already do wonders. You can top that off with spinning off a few web-workers that also do the same:
If you set x=0n this will use up more memory (due to BigInts allowing much larger numbers and much more memory)
let x=0;
while(true){
++x;
}
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
Keep in mind that a website by default only uses 1 thread of your CPU. Hence why web-workers to block more threads would be good. :)
You could also add a setInterval/setTimeout in the loop or other things to let the browser have time to repaint to be responsive if you want to hide it better to prevent the browser from prompting to end the unresponsive page.
Edit: You might want to consider adding some actual IO tasks (especially to the harddrive) to really slow it down.
If I remember correctly, there was a bug at one point that was being abused by downloading nearly infinite 0byte files to the host computer to essentially crash it.
This will hold up the CPU less than the initial infinite loop, but will leave the page responsive enough for the browser to not prompt to kill the script.
const wait = () => new Promise((res) => setTimeout(() => res(), 0));
async function timeWaster() {
let x = 0n;
while (true) {
x++;
if (x % 10000000n === 0n) {
await wait();
}
}
}
timeWaster()

JavaScript: changing timeout for infinite loops?

Sometimes I make mistakes and get infinite loops in JavaScript (example: while(true){}). Firefox helpfully reports "Error: Script terminated by timeout" or that the memory allocation limit is exceeded. How can I change the length of this timeout? I want to shorten it during development.
I could also solve this problem by writing a function that I call inside the loop that counts iterations and throws an exception on too many iterations. But I'm also interested in how to change the timeout value.
I have not seen this timeout documented, and have not found it by searching.
Unfortunately the maximum recursion limit is not user configurable from within a page running javascript. The limits also vary across browsers.
This Browserscope test showcases the results of user testing from another StackOverflow question on the subject: What are the js recursion limits for Firefox, Chrome, Safari, IE, etc?
Aside from writing your own timeout or utilising a promise chain to process data, you won't be able to change the timeout yourself.
There are multiple ways to change the timeout of infinite loops.
One shorter method is setInterval:
setInterval(function() {
document.body.innerHTML += "Hello!<br>";
}, 1000) //This number is, in milliseconds, the interval in which the function is executed.
Another better method is window.requestAnimationFrame. This gives you a higher quality animation(see Why is requestAnimationFrame better than setInterval or setTimeout for more details); here's an example of it in motion:
function run() {
setTimeout(function() {
window.requestAnimationFrame(run);
document.body.innerHTML += "Hello!<br>";
}, 1000); // This sets an interval for the animation to run; if you take the setTimeout out the function will loop as quickly as possible without breaking the browser.
}
run();
D. Joe is correct. In Firefox, browse to about:config and change the number of seconds value in dom.max_script_run_time .
See http://kb.mozillazine.org/Dom.max_script_run_time for details--you can also eliminate the timeout.
This will partially answer your question, but here is how I handle such case. It is more a workaround than a fix.
IMPORTANT: Do not put this code in production environment. It should only be used in local dev while debugging.
As I tend to be debugging when I stumble upon this kind of case, I am mostly likely using console.log to output to console. As such, I override the console.log function as follow anywhere near the entry point of my app:
const log = console.log
const maxLogCount = 200
let currentLogCount = 0
console.log = function (...msg) {
if (currentLogCount >= maxLogCount) {
throw new Error('Maximum console log count reached')
}
currentLogCount++
log(...msg)
}
Then when I accidentally do this
while (true) {
console.log("what is going on?")
}
It will error out after 200 outputs. This will prevent the tab from locking for half a minute and having to reopen a new tab and bla bla bla.
It is usually just the browser's way of saying the script is out of memory. You could solve this by using for loops or creating and index variable and adding to it each time like so:
var index = 0;
while(true){
if(index > certainAmount){
break;
}
index++;
}
If you really want something to go on forever read about setInterval()
or setTimeout()

requestAnimationFrame called right before the end of the frame?

I've been experimenting with jank-free rendering of complex scenes on HTML5 canvas. The idea is to split rendering into multiple batches with each batch taking a maximum of, say 12 ms, so that the concurrently running animations (very cheap to execute) are not interrupted.
Conceptually, batch-rendering is implemented like this:
function draw(ctx) {
var deadline = window.performance.now() + 12; // inaccurate, but enough for the example
var i = 0;
requestAnimationFrame(function drawWithDeadline() {
for (; i < itemsToRender.length; i++) {
if (window.performance.now() >= deadline) {
requestAnimationFrame(drawWithDeadline);
return;
}
var item = itemsToDraw[i];
// Draw item
}
});
}
The complete code is in this JSFiddle: https://jsfiddle.net/fkfnjrc2/5/. The code does the following things:
On each frame, modify the CSS transform property of the canvas (which is an example of the concurrently-running fast-to-execute animation).
Once in a while, initiate re-rendering of the canvas in the batched fashion as shown above.
Unfortunately, I'm seeing horrible janks exactly at the times when canvas contents is re-rendered. What I don't seem to be able to explain is what the Chrome Developer Tools timeline looks like:
The dropped frames seem to be caused by the fact that the requestAnimationFrame is not called right at the start of the frame, but towards the end of the ideal 16ms period. If the callback started right after the previous frame completed rendering, the code would most likely complete in time.
Rendering to an off-screen canvas (https://jsfiddle.net/fkfnjrc2/6/) and then copying the complete image to the screen canvas helps a little, but the janks are still there with exactly the same characteristics (delayed execution of rAF callback).
What is wrong with that code? Or maybe something's wrong with my browser / machine? I'm seeing the same behaviour on Chrome (49.0.2623.112) on Windows 10 and Mac OS.
The issues seem to be caused by Chrome's specific requestAnimationFrame callback scheduling. I've filed a bug to track this, it contains some simpler reproduction code examples.

performance of webview using javascript timer is not good

I am a student who is studying webview on android.
as I am a foreigner, I will thank you if you consider my mistakes on grammer...
I encountered a problem on making webview.
it is its "performance" when I use timer(setInterval method).
I am making a shooting game which is like "1945 strikers".
I made a effect which shows explosion-images using "Timer"(setInterval).
(This effect shows 14-pictures in order rapidly)
but, the problem is that my mobile phone can not show that effect naturally.
(it is stopped little by little)
I can not understand what is wrong.
exactly, I reduced "new" methods by using "pop" and turned off sounds.
I guess that the problem is based on the number of timer.
In my game, each bullet which hitted enemy occur explosion Timer.
and I duplicated this Timer to 10 as I thought it was not enough.
source code is like this.
=====call animation=======================
function drawCrash(x,y){
if (crashCount1 == 0) {
crashHereX = x;
crashHereY = y;
crashTimer1 = window.setInterval(crashAnimation1, interval);
crashCount1++;
}
else if (crashCount2 == 0) {
crashHereX2 = x;
crashHereY2 = y;
crashTimer2 = window.setInterval(crashAnimation2, interval);
crashCount2++;
}
... (total 10 methods)
======explosion animation==========================
function crashAnimation1() {
this.crashList=[crash01,crash02,crash03,crash04,crash05,
crash06,crash07,crash08,crash09,crash10,
crash11,crash12,crash13,crash14];
if (crashCount1 >= 13) {
window.clearInterval(crashTimer1);
crashCount1 = 0;
} else {
crashCount1+=1;
}
this.context.drawImage(this.crashList[crashCount1],crashHereX,crashHereY,50,50);
}
function crashAnimation2() {
this.crashList=[crash01,crash02,crash03,crash04,crash05,
crash06,crash07,crash08,crash09,crash10,
crash11,crash12,crash13,crash14];
if (crashCount2 >= 13) {
window.clearInterval(crashTimer2);
crashCount2 = 0;
} else {
crashCount2+=1;
}
this.context.drawImage(this.crashList[crashCount2],crashHereX2,crashHereY2,50,50);
}
... (total 10 methods)
is there anything which makes my game slow?
I have been debugging my source code using Chrome,(using F12 key)
but my laptop computer performs my source code well.
there isn't any problem!
you must hard to understand what I am saying...
what I want to know are like this.
should I reduce setInterval method to show the game performance naturally?
but, previous version (android 4.1.2) had NO problem! it performed naturally!
Now, I am using kitkat version(4.4.2)... I really hate this version.
Even I tried to downgrade my android phone!
it was hard for me to find "e.preventDefault();" it took 3-days for me to find...
is there anything which is better to debug JavaScript?(I am using Chrome F12 key)
is the "splice(index,1);" method occur "stopped phenomenon"(which I said above, "not natural")
when it is used many time? (in my game, many bullets are created and removed(new and splice))
I really want to know how to solve this problem...
Thank you very much.

Categories

Resources