p5.js autoclicker calling - javascript

I have a simple question maybe, I was for days looking for solution and don't want to waste your time, but isn't work for me so I'm here now.
Im using P5JS, and I wanted to create auto click function.
There how I call an button in sketch.js file
var button1 = createButton("Generator");
button1.mousePressed(banana);
button1.id('autoclick');
Here you can see how I call in index.html
Im trying something like this:
<script type="text/javascript">
var iteration = true;
var time = new Date();
var delay = 5000; // 5 secondes
while(iteration) {
if(time.getTime() + 5000 < new Date().getTime()) {
iteration = false;
}
}
document.getElementByID('autoclick').click();
// noprotect
</script>
Maybe I complicate to much? any suggetions? thank you!

Your while loop is blocking, which means that while Javascript is running your while loop, it will not be able to execute any other code. You want to use setInterval() for your purposes.
For example,
setInterval(() => console.log("hello!"), 1000)

Related

Why/How is my code causing a memory leak?

I have written the following JavaScipt code within a Spotfire TextArea. I include the application and tag for completeness, but I don't believe my issue is Spotfire-specific. Essentially, I have a timer which runs every 5 minutes, and clicks on a link (clickLink('Foo');) to trigger execution of some Python code elsewhere in the application. If the application also contains a timestamp of the last full update, which occurs every 30 minutes in the same manner (clickLink('Foo');):
function reportTimestamp() {
var timeNow = new Date();
var hoursNow = timeNow.getHours();
var minutesNow = timeNow.getMinutes();
var secondsNow = timeNow.getSeconds();
return hoursNow + ":" + minutesNow + ":" + secondsNow;
};
function timeBasedReaction(timestampAge){
if (timestampAge >= 1800) {
clickLink('Foo');
clickLink('Bar');
} else if (timestampAge >= 300) {
clickLink('Foo');
};
};
/*
function timeBasedReaction_B(timestampAge){
if (timestampAge >= 300) {
clickLink('Foo');
if (timestampAge >= 1800) {
clickLink('Bar');
};
};
};
*/
function clickLink(linkName) {
var clickTarget = document.getElementById(linkName).children[0];
clickTarget.click();
};
function checkTimestampAge() {
console.log(reportTimestamp());
var myTimeStamp = document.getElementById('Timestamp').children[0]
var timeStampMS = new Date(myTimeStamp.textContent).getTime();
var currentDateMS = new Date().getTime();
var timestampAgeSeconds = (currentDateMS - timeStampMS)/1000;
timeBasedReaction(timestampAgeSeconds);
};
function pageInitialization() {
checkTimestampAge();
var myTimer = null;
var timerInterval = 300000;
myTimer = setInterval(function(){checkTimestampAge()},timerInterval);
}
pageInitialization();
For reasons unclear to me, running this code in the application or in a web browser starts off fine, but eventually leads to very large memory allocation.
I've tried to read
4 Types of Memory Leaks in JavaScript and How to Get Rid Of Them,
JS setInterval/setTimeout Tutorial, and
An interesting kind of JavaScript memory leak, and it's a start, but I don't know enough to really understand what I'm doing wrong and how to correct it.
Thanks, and sorry for the huge block of text.
This causes a memory leak because of how Spotfire handles Javascript which has been associated with/loaded into a TextArea.
Both in the desktop client, as well as in the Webplayer instance, when the page is loaded, all the portions of that page are loaded, include the TextArea and including the Javascript associated therein. My previous understanding in the comments above:
"the code is intended to run when the page loads, and it was my understanding that it would stop/be cleared if the page was re-loaded or someone navigated away from it"
was incorrect. One of the script's actions was to update/redraw the HTML location in the TextArea. This, in turn, reloads the TextArea but does not clear the existing Javascript code. However, it's not really accessible anymore, either, since var myTimer = null actually creates a new myTimer rather than nulling-out the existing one. In this way, instances of myTimer increase geometrically as instances of function timeBasedReaction run and continually update the underlying TextArea and load in more of the same Javascript.
To anyone who ha a similar issue and come here, it's been over 3 months and I haven't figured out how to solve this once and for all. If I do, I'll try to come back with another update.

Looping function works 20 times in javascript, but then returns NaN

run = 0
function getLowestPrice(id){
$.get('/items/' + id + '/privatesaleslist', function(data){
var html = $(data);
var lowestPrice = parseInt($('.currency-robux', html).eq(0).text().replace(',', ''));
console.log(lowestPrice);
})
}
while (run < 100)
{
getLowestPrice(362081769);
run = run + 1
}
Webpage I am using this code on: https://m.roblox.com/items/362081769
What happens is when I run this code it runs successfully 20 times returning 3997, and then I get spammed with "NaN" Image.
What i'm trying to get this program to do is check the price of the item for as long as I want, and report it in the chrome console. Why does the function work 20 times and then just return NaN?
I am a beginner at javascript, so please explain your solutions so a beginner like me can understand.
Thanks :)
Hey man I think part of your issue is in the while loop mechanic. Whenever run hits 100 your function will stop being called.
You could use a setInterval function. How this work is it will call whichever function you pass it, every "x" milliseconds.
setInterval will call getLowestPrice with the id of 362081769, every 5 seconds.
const id = 362081769
function getLowestPrice(){
$.get('/items/' + id + '/privatesaleslist', function(data){
var html = $(data);
var lowestPrice = parseInt($('.currency-robux', html).eq(0).text().replace(',', ''));
console.log(lowestPrice);
})
}
setInterval(getLowestPrice, 5000);
Also here is a link to the formal setInterval documentation.
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
I hope this helps :)

Javascript - Run a code nonstopable via Chrome Console including refreshing

I want to run a javascript code via the Chrome's Console.
var word_idx = 0;
var interval_per_word = 250; // in milliseconds
function DoIT(){
if(word_idx<words.length){
$('#inputfield').val(words[word_idx] + ' ');
var keyup = jQuery.Event('keyup');
keyup.which = 32;
$('#inputfield').trigger(keyup);
word_idx++;
setTimeout('DoIT()', interval_per_word);
}
}
DoIT();
Now, I'm trying to do that every minute, the code will refresh the page and use the function "DoIT" again.
Any help? I can't think of any idea, tried using location.refresh() with no success.
I'll be glad for help, thanks!

setInterval, animating multiple images, stopping setInterval

I need to create some animation using DHTML/Javascript and I am struggling to get anything I do to work. My parameters are it must use the setInterval function, a user defined function and 8 jpg files. There must also be a way of stopping the animation.
If someone could get me pointed in the right direction I would be very happy. I have not been able to find suitable information on how to do this so far and I am still fairly new to Javascript. Thanks.
Sorry for not posting code earlier. It was such a mess I didn't want to embarrass myself. Here's what I have. It's not working.
var slideShow = ['images/pic0.jpg','images/pic1.jpg','images/pic2.jpg','images/pic3.jpg','images/pic4.jpg','images/pic5.jpg','images/pic6.jpg','images/pic7.jpg'];
picO = new Array();
for(i=0; i < slideShow.length; i++) {
picO[i] = new Image();
picO[i].src = slideShow[i];
}
var curPic = -1;
function changeImage(){
curPic = (++curPic > slideShow.length-1)? 0 : curPic;
imgO.src = picO[curPic].src;
setInterval(changeImage,100);
}
window.onload=function(){
imgO = document.getElementById("imgAnim");
changeImage();
}
var t=setTimeout(function(){alert("Welcome to my animated page")},3000)
The other thing it needs to do is pop up an alert box 3 seconds after the animation starts. It's doing that but it's popping up EVERY 3 seconds, which is not what I want.
Thanks for your help so far. I've done pretty well with my Javascript work lately but this one is just something I'm not that familiar with.
To the using of setInterval and stopping the animation
var animation = setInterval(yourAnimation,500); // run yourAnimation every 500ms
clearInterval(animation); // stop animation
To the animation
var slideShow = ["img1.jpg","img2.jpg", ... ,"img8.jpg"];
var counter = 0;
function yourAnimation() {someImage.src = slideShow[++counter%slideShow.length];}

Suggest a way to update time every minute

I have a full ajax application. i am using the below code to update time every minute. But if i keep the browser open for >10 min the browser becomes non responsive/slow. Suggest a better code.
function tick()
{
var d = new Date();
var time = padNumber(d.getHours(),2)+':'+padNumber(d.getMinutes(),2);
$('#WeatherBoLfTime').html(' '+time);
t = setInterval('tick()',60000);
}
$(document).ready(function(){
tick();
})
The problem is that you're calling setInterval many times and never clearing any of them. So after a while you have lots of interval callbacks running at around the same time.
Change
t = setInterval('tick()',60000);
to
t = setTimeout(tick,60000);
When I first started out coding JavaScript I took down a Lycos web server with AJAX calls because I made the same mistake :-)
Note that since you're displaying the actual time, you should use a much shorter timer than 1 minute. If I land on your webpage at 13:42:30, the time will not be updated until ~13:43:30. To keep it in sync with the machine's time, you would probably want to set the timer for 1000.
setInterval() sets an interval. You only need to set it up once, it will get called every 60000ms automatically. setTimeout() is the one you have to setup every time again.
As others have pointed out, you are creating new interval every time.
Move it to outside your function.
function tick()
{
var d = new Date();
var time = padNumber(d.getHours(),2)+':'+padNumber(d.getMinutes(),2);
$('#WeatherBoLfTime').html(' '+time);
}
$(document).ready(function(){
t = setInterval(tick,60000);
})
Edit: I'm slow and other answers seem to be updated. So this one is useless now :)
Have look in below demo code, which will be updated each second...
<!DOCTYPE html>
<html>
<head>
<title>j</title>
<script type="text/javascript">
function myFunction()
{
setInterval(function(){
var d = new Date();
document.getElementById("dates").innerHTML = new Date(d.getTime());}, 1000);
}
</script>
</head>
<body>
<input type="button" name="e" onclick="myFunction()">
<p id= "dates">ok</p>
</body>
</html>

Categories

Resources