Is there any solution to end an endless loop function? - javascript

Is there any solution to escape from the endless function, code like this:
var endless = function(){
while(true){};
}
killWhenTimout(endless, 5000);
I am looking for a solution like killWhenTimeout, killWhenTimeout will kill the loop if time is out.
Any suggest will be appreciated.

If endless function doesn't require any special API, for example manipulating DOM, you could run it within a WebWorker. And then terminate it after the timeout, if it is still running.
Take a look at this article for details - https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers.

Related

MOUSEOVER: How to start a function and let it play until the end without start it over and over?

I want to start a function when I over mouse an ID #show-details.
But I need it to start only one until it ends, not to start over and over again ...
With my code below It starts when I mouseover it but starts over and over even if it doesn't finish.
I need some help :)
function showDetails() {
var details = document.getElementById('show-details');
details.addEventListener('mouseover', initDetailsLetters);
}
i think you need a flag, if the flag doesnt exist then create it and start over, if it does exist then dont run the code
Try a callback function, I have found this example to help you: Proper way to wait for one function to finish before continuing?
This looks similar to your problem

How to stop a setInterval Loop in Javascript outside of code without refreshing the browser?

This may be a quite naive question but I really need some help.
Prior to writing this post, I was programming on JSBin. Turns out without me realizing, I ran a setInterval loop prompting for userInput and it kept on looping, making me unable to click anywhere to change the code to fix the loop. It kept on repeating and repeating. It got to the point where I had to refresh and lose all my hard-written-code (I was not logged in, so my code was not saved)! I want to avoid that next time.
So, my question is how do I stop any such kind of setInterval Loops, so that I am able to access my code and change it and re-run it. Below is a code that demonstrates my issue, if you try running it on JSBin.com (obviously, it is not the code I wrote before). As you can see, I can not click on my code to change it (or save it) in any way, which means I lose all my code!
This may seem like a useless question, but I really want to know ways to fix it and perhaps fixing it from the developer tools will help me be familiar with the overwhelming set of tools it has :P. So please help me if you know a solution.
Thank you for taking your time to help me! I appreciate it.
setInterval(demo,1);
function demo()
{
var name = prompt("Enter your name: ");
}
Another option is to search the developer tools "Elements" panel for the iframe (this should be doable even if the main document is unresponsive due to prompt's blocking) - then, just right click the iframe element and remove it, no need to type any Javascript. (or, if you want you can select the iframe with querySelector and remove it, eg document.querySelector('iframe').remove())
That's kind of a hack and should only be used in cases like the one exposed in OP but,
About all implementations use integers as timerid that just get incremented at every call.
So what you can do, is to clear all timeouts that were created on the page.
To do so you need to first get to which timerid we are, then call cleatTimeout or clearInterval (they do the same) in a loop until you reach the last call:
function stopAllTimers() {
const timerid = setTimeout(_=>{}); // first grab the current id
let i=0;
while(i < timerid) {
clearTimeout(i); // clear all
i++;
}
};
btn.onclick = stopAllTimers;
// some stoopid orphan intervals
setInterval(()=>console.log('5000'), 5000);
setInterval(()=>console.log('1000'), 1000);
setInterval(()=>console.log('3000'), 3000);
const recursive = () => {
console.log('recursive timeout');
setTimeout(recursive, 5000);
};
recursive();
<button id="btn">stop all timeouts</button>
Assuming the dev tools are closed, hit esc and f12 nearly simultaneously. This should open the dev tools. If it doesn't keep trying until it does.
Once they are open, hit esc and f8. Again, retry til it halts javascript execution at some arbitrary point in the code.
In the "sources" tab locate the generated script for what you wrote (offhand I don't know how it would look like from within JSBin) and literally delete the var name = prompt("Enter your name: "); line. Hitting f8 again will continue execution as if the "new" code is running. This should free you up to copy/paste your code from the site itself before you refresh the page

Check Javascript Condition Every Frame

Pretty much, my question is simple, and I did search for a similar question before posting this. I would like to know how to make Javascript code repeatedly execute while the page is open, rather than the code running once and being done or only responding to event handlers. I pretty much want the Javascript equivilant of:
$(document).ready(function() {
});
But I do not want to use Jquery because it is less efficient. I want to check an === condition every single frame.
Use SetInterval .. inside a window.onload function
window.onload = function() {
function test() {
alert("test");
}
setInterval(test, time_miliseconds);
}
setInterval(function(){
var blah = whatever;
if (done){
clearInterval();
}
},time_in_milliseconds);
loop keeps looping per your milliseconds argument. If you want a loop thinner than a millisecond or as hard as the computer can do it then just a regular while(true){} will suffice.

Loop binding to find number of loops

I could not find this in the buzz.js documentation but is there any bindings for the loop event. Something like
soundObject.bind('looping', function(e){
});
I am looking to see how many times the sound object has looped, if anyone with knowledge around this library has a workaround that would also help. I tried to bind to the ended event but that doesn't work?
EDIT:
I am thinking as a hack that i could bind to the playing event and use the getPercent() method to see when i have hit 100 and keep a counter to find number of loops?
Since there are no events that trigger with the loop option, then why not implement your own loop functionality by binding to the ended event and than calling play() again, this way you know when each play has finished.
var loopCount = 0;
var mySound = new buzz.sound("my_cool_sound").bind('ended', function () {
loopCount++;
this.play();
}).play();
Demo fiddle
Edit 1:
True. My older answer doesn't function as I thought it might :). Having read the source, they don't seem to trigger any public events. Though they do seem to bind to some private one, ended.buzzloop. I couldn't find the said event being trigger in code, but maybe it might work for you
As #koala suggested, implementing your own loop might turn out to be a better option.
Old answer - doesn't work!
I haven't used buzz.js before. Reading the docs, I found the playing & paused events.
playing
Sent when the media begins to play (either for the first time, after having been paused, or after ending and then restarting).
My idea is to listen to these two events. If playing is raised without a pause having been raised, then you can increment your count.

slow down execution of javascript's eval

I have created a little robot like the Karel robot (Wikipedia) which is based on javascript.
Karel4Web
The robot can be controlled with some simple commands such as "forward", "turnright" and so on.
The user can write a javascript program to control the robot which then goes through javascripts "eval()" function so that the robot moves.
The problem is that I want the robot to move slowly so that you can see what he is doing and so that you can highlight the current code line in the editor.
Current method: Parsing
At the moment I have solved this (in the offline version) by parsing each line in the textarea and then building a stack of action which are then executed one after another with window.setTimeout. But this is of course limited because I have to write parsing code for every little javascript language contruct which is much work and error prone.
Some additional information to this:
Parsing version: http://abi-physik.de/_niki2/niki.php
Parsing version js code: http://abi-physik.de/_niki2/js/niki.js
Important functions are at the bottom of the script: run(), execute()
I am currently parsing the user script line by line and adding the actions to a stack. If the parser encounters an "if" it will begin a new stack and add all actions to that stack. if the parser then encounters an "}" it will close the "if" stack and continue to add actions to the base stack.
Any idea to improve this?
I would say have those functions register to some queue instead of having them execute the JavaScript directly.
var moveQueue = [];
function forward(){
moveQueue.push(_forward);
}
function _forward(){
alert("move forward");
}
function backward(){
moveQueue.push(_backward);
}
function _backward(){
alert("move backward");
}
Than when it runs you would use a setTimeout and
function run(){
var curStep = 0;
function go(){
moveQueue[curStep]();
curStep++;
if(curStep<moveQueue.length){
window.setTimeout(go,500);
}
}
}
You still would need to parse it out to figure out the if statement logic, but this is one of many ways that will allow you to control the speed of execution.
Javascript doesn't have a sleep() function, so yes, using setTimeout or setInterval is the way to go.
You could parse the 'instructions' first, assemble an array of actions that need to be carried out, then use setInterval to arrange for a function to be regularly called which takes the next instruction and carries it out (or clears the interval, if there are no more instructions waiting to be processed).

Categories