Check Javascript Condition Every Frame - javascript

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.

Related

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

Problem with a do-while loop and creating an alert

I'm new to javascript and I'm trying to make a program to continuosly click one button unless another button is present. (I'd also love to get an alert when the second button appears but I don't know how to do that.)
This is what I got:
Do {Let button=document.getElementById("find");
Let want= document.getElementById("bba");
setInterval(function(){
button.click();
}, 10000); }
while (want.click=false)
I keep getting errors (unidentified syntex). I'm not sure how to fix it.
Any help will be greatly appreciated!
What you should do is use a single setInterval :
window.setInterval(function() {
if (!document.getElementById("button2")) {
document.getElementById("button1").click();
} else {
document.getElementById("button2").click();
alert("second button appeared");
}
}, 100);
Sorry for formatting, I'm on mobile.
Just from looking over your code I see two main errors. The first is that you used a capital do and let, JavaScript is case sensitive so you need to use lowercase. The second is that in you wrote
while (want.click=false)
What you wrote is an assignment not a equality check.
while (want.click == false)
That's the correct way to write it.
Your do and let keywords are capitalized. They should be lower case.
Let want= document.`getElementById`("bba");
You should use a triple equal sign here rather than an assignment operator.
it should be: let want === document.getElementById("bba");

display current value of var to HTML

I have a variable speed controlled by the user from keyboard, and I want to display it current value all the time.
I tried:
var user_speed= 1; //init
<h3 style="float:left;" id="userspeed"></h3>
document.getElementById("userspeed").innerHTML = user_speed.toFixed(2);
but what I get is only speed = 1 and it never changed.
Is there a way to keep changing the displayed value, without creating a function that fire each time the user change the speed and execute document.getElementById()... again?
Why not use setInterval to update the value like so:
var speed = 1; //init
setInterval(function(){
document.getElementById("userspeed").innerHTML = user_speed.toFixed(2);
}, 1000);
This will update the value every 1 second (1000 ms).
You are only getting the initial value, because you are calling only once that code.
As you said, if you want to change the value you should need to create a call to that function in order to renew the value.
I think there is no way around. You may have to use a function and an event. Because how would you know or trigger some calculation when you dont know on which point the user entered some keys?
See this question
UPDATE: As you maybe know setInterval/setTimeout are evil!
If you take a look at this link, you will see that you should avoid those functions for not very good reasons. Simplified:
... The first argument is a string, you actually pass it some JavaScript that will be evaluated at a global namespace when the timer expires. Read the evils of evals again above and then come back. The good thing is that you are not required to pass in a string of JavaScript code. ...

style.display changing after Array Sort

I want to display a simple loading message before a sort, but the display changes from none to block after the sort even though I call the sort after. I even tried using setTimeout (2 seconds) to change the display then call a dummy function to sort the stuff.
function sort(i) {
document.getElementById("loading").style.display = "block";
array.sort(function(a, b) {
return a[i].localeCompare(b[i]);
});
}
Browsers don't rush to repaint the page while JS is busy working (on the assumption that there will probably be other DOM changes that they should batch together for the repaint).
You'll need to free up the event loop to allow a repaint between your two statements.
Move the call to array.sort into a function and call it after a delay (e.g. with setTimeout or requestAnimationFrame).

Is there any solution to end an endless loop function?

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.

Categories