Need help understanding javascript code/jquery - javascript

So apparently the following can be used to automate linkedin steps of unfollowing a contact. I tried to run this code in the Chrome Console, and I'm not sure if it works. So I need help from someone who knows Javascript and JQuery to understand what this does, and then I can modify it to make it work.
var buttons = $("button"),
interval = setInterval(function(){
var btn = $('.is-following');
console.log("Clicking:", btn);
btn.click();
if (buttons.length === 0) {
clearInterval(interval);
}
}, 1000);
PS: The linkedin page that lets to unfollow your contacts is below. Login, and then navigate to the below.
https://www.linkedin.com/mynetwork/invite-connect/connections/

First, it selects all the buttons and stores them on the variable buttons ($("TAG") will select elements with the tag TAG). Then, it creates an interval that will be stored in the variable interval (bad practice, btw, because it isn't using "var" to declare the variable, so, it's a global variable, that should be avoided... but it's necessary to declare it as global in order to use clearInterval) that will execute the function inside the setInterval function call every second (1000 ms). That function will get all the elements that have the class "is-following" and will store them on the variable btn. Then, it will log the... buttons? After that, it will execute the click event on all of those buttons. Finally it will check if the amount of buttons are 0. If true, it'll stop the interval.

Related

Javascript - how to create a timed redirect button and a different button to cancel it

I have the following code. Pressing the first button sends the user to a different URL after 10 seconds.
However, I am also trying to get the second button to cancel that redirect if pressed before those 10 seconds. This doesn't seem to work and the URL redirect still occurs.
I have looked online for various solutions and I am unable to get anything to work. I have also tried swapping out setTimeout/clearTimeout with setInterval/clearInterval and other variations of the code.
I would be willing to have the code changed completely or use Jquery instead etc. I have been trying to do this for past couple of days so any help would be greatly appreciated.
If the redirect countdown could also start again from 10 seconds if the first button is pressed again after pressing the second button, that would be also great.
Javascript
<script>
var redirectTime = "10000";
var redirectURL = "https://realmbound.com";
function timedRedirect() {
var timeoutHandle = window.setTimeout("location.href = redirectURL;",redirectTime);
}
function stopTimer() {
clearTimeout(timeoutHandle);
}
</script>
HTML
<button onclick="JavaScript:timedRedirect()">Click me for a timed redirect.</button>
<button onclick="JavaScript:stopTimer()">Stop Timer.</button>
Your timeoutHandle is in scope function, you must delcare it to global scope it in your order to access it on stopTimer().
let redirectTime = "1000";
let redirectURL = "https://realmbound.com";
let timeoutHandle;
function timedRedirect() {
timeoutHandle = window.setTimeout("location.href = redirectURL;",redirectTime);
}
function stopTimer() {
clearTimeout(timeoutHandle);
}
<button onclick="JavaScript:timedRedirect()">Click me for a timed redirect.</button>
<button onclick="JavaScript:stopTimer()">Stop Timer.</button>
The rest of the code is fine.
Your solution is correct, only thing that you missed is to scope timeoutHandle variable as global scope so that stopTimer function can access it.
here is the working fixed version of your solution:
https://jsfiddle.net/8uw7f19k/1/
Hope it helps ;-)

How to stop repeating of variables of "setInterval" Javascript

I'm a beginner at JS , Now am programming a javascript app
in the app there is a button when the user clicks on it, a door supposed to be opened for 10 seconds then close again
I used "set interval" to do this function by :
var rVars = []
rVars.push( {name:"door", val:1} ) // 1 for open , 0 for close
_server.setRoomVariables(r, user, rVars)
var params = {}
params.user = user
params.r = r
myInterval = setInterval("TimeForClose", 20000, params)
This is the code responsible for closing the door after 10 seconds
function TimeForClose(params){
var rVars = []
rVars.push( {name:"door", val:0} )
_server.setRoomVariables(params.r, params.user, rVars)}
And it was done successfully, but the problem was that I found the function "TimeForclose" repeats every 10 seconds , which makes when another user click on the button and door opens for him, the first one repeated function which still repeats will close the door for the second user too and both functions of each of them will be repeated , and so on .
So I read I have to use "clear interval" or timer to stop repeating but when I used it, it didn't stop the repeating so I think I used it Incorrectly
So what's the best way to stop repeating? ( I just want the function to occurs once when someone click on a button then it stops ) .
I hope you give me the correct syntax of the code
Yes, as u said u can use clearInterval() after closing of that door window, try that once
If you need to only execute once, you can use setTimeout
change setIntervalm to setTimeout
myInterval = setTimeout("TimeForClose", 20000, params)
The function is only executed once. If you need to repeat execution, use the setInterval() method.
If you need to repeat excution and stop based on some external event you can use clearTimeout()

youtube repeat oneliner

I am trying to make a oneliner to repeat videos.
I started looking for that replay button to trigger another round:
$("[title='Replay']")[0].click();
A self calling function to loop in the background while the vid is running.
rpt=function(){setTimeout(function(){alert("blarg");rpt()},5000)}
putting those two things together and adding a tiny bit of fluff:
$ = jQuery to initialize shiny $()-syntax and finally rpt();to get things rolling:
$=jQuery,rpt=function(){setTimeout(function(){$("[title='Replay']")[0].click(),rpt()},100)};rpt();
alas, the parts work but not the whole thing
I noticed that the console is printing an error message if I enter the final line before the video has finished; since the button is not found yet and therefore a call to .click() on undefined isn't working.
Shouldn't the function still loop in the background and trigger during a later call, as soon as the replay button is there for jQuery to grab?
I'm using chrome 44.0.2403.130 and jQuery: 1.10.1
Add a verification to make sure there is a replay element available.
Use setInterval() instead of setTimeout().
By default (and unless you use other conflicting libraries), jQuery is assigned to the $ variable on its initialization.
setInterval(function(){if($("[title='Replay']").length)$("[title='Replay']").trigger('click');},100);
one line repeat + number of repeat appended in title:
var title=$('#eow-title').innerHTML; var replaysN = 1; setInterval(function(){if($('.ytp-play-button').title == 'Replay') {$('.ytp-play-button').click();$('#eow-title').innerHTML = title+' (x'+replaysN+')';replaysN++;} }, 1000);
..after some weeks after making this post, there was a new feature in youtube :D
After right-click on video -> Loop
So every customization is useless :)

Within Google apps script, what replaces Utilities.sleep() to prevent double clicks?

I'm writing an add-on within Google Docs Script. From a sidebar, it writes info into the Doc, not a spreadsheet. Depending on connection speeds, the Doc is updated between <1 sec and 5 secs with the info.
My issue is with user double clicks. I can disable the button; however, the script takes less than a second to complete, yet the Doc is updated in > 1 sec. The finished script enables the button. The user clicks the button again and the script attempts to write the info for the first time. The end result is a double entry.
My solution thoughts were: 1. a wait or pause 2. a callback function or 3. Locks.
Issues:
Callback: I couldn't figure out what event/input I could use to tell the script to unlock the button now. I could do an infinite loop that constantly checks forever until the Doc has been updated, but that didn't seem like a solid solution.
Lock: There isn't anything there to simply just wait. It can wait for the function to become available, but that isn't a problem. The problem is the script is done to fast relative to the Doc update.
Any thoughts?
Thanks.
I think of this solution:
Each time the script is called, you compare document's current text with the text which was passed to your script on the previous call.
Some pseudo code:
var previousText = "";
function addEntry() {
var body = DocumentApp.getActiveDocument().getBody();
var currentText = body.getText();
if (currentText === previousText) {
// Enable button here
return;
}
// Add entry to document AND currentText
// ...
// ...
previousText = currentText; // Save the text for future checks
// Enable button here
}
function onButtonClick(e) {
addEntry();
// Disable button here
}
I got it. I didn't realize the .withSuccessHandler also waited for the Doc to be updated. I assumed it only waited for the .saveSettings(settings) to finish. Now the SuccessHandler(enablesButton) at the appropriate time to prevent double clicks.
google.script.run.withFailureHandler(onFailure).withSuccessHandler(enableButton)
.saveSettings(settings);

document.getElementById does not return null, but also does not do what I want. No error in javascript console

In this instance, I load a single paypal page, in which I am prompted to login. Once I login, the page changes, through the use of other javascripts on paypal's end. The address does not change on this transition, nor does the source code in any material way. I am trying to find a way to have my script wait long enough after the first click to be able to get the element that loads after. I thought I could do this fairly simple using the following:
document.getElementById("submitLogin").click();
window.onload = function() {
document.getElementById("continue").click();
};
When the script is executed, the first button is clicked, the page transitions, but it won't click the second button that loads. My javascript console does not report any errors, suggesting that it is able to "get" the element. Not sure why it won't click it though.
If nothing else, you could always poll for the existence of the "continue" element at some interval:
function clickContinue() {
var button = document.getElementById("continue");
return button ? button.click() : setTimeout(clickContinue, 100);
}
document.getElementById("submitLogin").click();
clickContinue();
If you go this route, you'll probably want to include a failsafe so it doesn't run too long, in case something unexpected happens. Something like this should work:
clickContinue.interval = 100; // Look for "continue" button every 0.1 second
clickContinue.ttl = 10000; // Approximate time to live: 10 seconds ~ 10,000 ms
clickContinue.tries = clickContinue.ttl / clickContinue.interval | 0;
function clickContinue() {
var button = document.getElementById("continue"),
interval = clickContinue.interval;
return button ? button.click() :
clickContinue.tries-- && setTimeout(clickContinue, interval);
}
// ...
Take a look at PayPal's API docs and see if they provide a way to set up a callback to handle this, though. This polling technique should probably only be used as a last resort.

Categories