How pause a loop in JavaScript? - javascript

Can anyone tell me why I'm not being able to pause the loop? The idea is to pause it for 5 seconds and then restart it. The code is bellow. Thanks!
let pics = [{
name: 'picture',
picture: 'https://images.unsplash.com/photo-1491555103944-7c647fd857e6?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80',
number: 1
},
{
name: 'picture',
picture: 'https://images.unsplash.com/photo-1495837174058-628aafc7d610?ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80',
number: 2
},
{
name: 'picture',
picture: 'https://images.unsplash.com/photo-1474314881477-04c4aac40a0e?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80',
number: 3
}
];
let pauseLoop = false;
function displayImage() {
let display = document.querySelector('#display');
let button = document.querySelectorAll('.pic');
for (let i = 0; i < button.length; i++) {
button[i].addEventListener('click', function() {
display.style.backgroundImage = "url('" + pics[i].picture + "')";
// THIS IS SUPPOSED TO PAUSE THE LOOP FOR 5 SECONDS AND THEN RESTART THE LOOP
pauseLoop = true;
setTimeout(function() {
pauseLoop = false;
console.log(pauseLoop)
}, 5000);
})
}
}
// create list inside nav
let createGalleryMeny = () => {
let nav = document.querySelector('#nav');
for (let i = 0; i < pics.length; i++) {
let img = document.createElement('DIV');
img.style.backgroundImage = "url('" + pics[i].picture + "')";
img.className = 'pic';
nav.appendChild(img)
}
}
// loop through every picture
function loopPics() {
let number = 0;
let display = document.querySelector('#display');
display.style.backgroundImage = "url('" + pics[pics.length - 1].picture + "')";
if (pauseLoop !== true) {
setInterval(function() {
display.style.backgroundImage = "url('" + pics[number].picture + "')";
number++
if (number === pics.length) {
number = 0
}
}, 2000)
}
}
(() => {
createGalleryMeny();
loopPics();
displayImage()
})();
This code is just a simple gallery and I wanna have the option to pause the loop when one clicks any picture in the gallery, display the clicked picture and restart the loop after 5 seconds.

Pause is not something you should want in Javascript, this blocks your whole code. You should create a function that will execute the code you want to repeat after X seconds. It can be a function which can call itself. If you do want to "wait" for a few seconds on a line of code it is possible.
Make the function async:
async function displayImage() {
And then wait for 5 seconds:
await new Promise(resolve => setTimeout(resolve, 5000));
But your code is binding a click in the for loop, and you want to reexecute that code part. Which will result in multiple click handlers on 1 button depending on the timing. Which will probably not result in what you want.

Related

how to implement click logic

hi everyone!
i have a map with dots MAP which every 3 seconds shows a block with info
a function that is already in progress, and I want the function to stop when clicking on a point and display an infoblock for me(and i did it).
sorry in advance below is my code
// map with dots
var isActive = 0;
var isLoading = 1;
const count = document.querySelectorAll("[data-id]");//circle svg around dot
function removeClass() {
let infoCards = document.querySelectorAll("[data-info-id]");// info page name of the project
infoCards.forEach((el) => {
el.classList.remove("show");
});
}
function removeCircle() {
count.forEach((el) => {
el.style.display = "none";
});
}
function ready() {
function setAround(percent, idx) {
removeCircle();
let beforeElemIdx = idx === 0 ? count.length - 1 : idx - 1;
let beforeElem = document.querySelector(
'[data-id="' + beforeElemIdx + '"]'
);
let elem = document.querySelector('[data-id="' + idx + '"]');
elem.style.display = "block";
elem.classList.remove('active-circle');
beforeElem.style.display = "block";
const math = 2 * Math.PI * elem.r.baseVal.value;
elem.style.strokeDasharray = `${math} 1000`;
let a = math * (1 - percent / 100);
elem.style.strokeDashoffset = a;
if (percent >= 99.5) {
removeClass();
let infoShow = document.querySelector(`[data-info-id="${idx}"]`);
infoShow.classList.add("show");
isLoading++;
if (isLoading === count.length) {
isLoading = 0;
}
}
}
requestAnimationFrame(draw);
function draw(t) {
let idx = isLoading;
requestAnimationFrame(draw);
setAround((t / 30) % 100, idx);//timer 3sec
}
}
document.addEventListener("DOMContentLoaded", ready);
and i did this
var dots = document.querySelectorAll(".dota");
var infoCards = document.querySelectorAll("[data-info-id]");
let circle = document.querySelectorAll('[data-id]');
dots.forEach((el) => {
el.addEventListener('click', () => {
let idx = el.dataset.dota;
let circle = el.dataset.dota;
showInfo(idx);
addCircle(idx);
});
});
function showInfo(idx) {
removeClass();
let elem = document.querySelector(`[data-info-id='${idx}']`);
elem.classList.add('show');
}
function addCircle(idx) {
let circle = document.querySelector(`[data-id='${idx}']`);
circle.classList.add('active-circle');
}
and if u want my site pls dm me i'll send my github page
PUG CODE
TY ALL!
Have you tried making a condition into the drawing function that pauses it?
If it's paused you can call another function that will draw the info of the specific dot only once and then create a condition in which it will resume the drawing normally.
When I used drawing function I've simply added a bool variable that stored if paused or not in the recursive function.

Make the `for` loop wait for each function to resolve

Page 1:
function tempWindow(text)
{
var w = window.open('https://example.com/?data='+text, '_blank');
var t = setInterval(() => {
if(w.closed)
{
clearInterval(t);
return true;
}
}, 100);
}
var list = ['text1', 'text2', 'text3'];
for(var i=0;i<list.length;i++)
{
tempWindow(list[i]);//Each loop iteration must wait for each window to close
}
Temporary window:
(function(){
setTimeout(() => {
window.close();
}, 5000);
})();
The code on page 1 should open three windows and send to each of them the strings text1, text2, text3, stored in the variable data.
These windows must not be opened at the same time. For this, setInterval checks every 100 milliseconds if the previous window has already been closed.
Therefore, the second window can only be opened after closing the first one and so on.
I believe that the tempWindow function could return a promise and that using await a solution would be possible, but I don't know how to do that.
use that code. it will wait until window is close
function tempWindow(text) {
return new Promise(resolve => {
var w = window.open('https://example.com/?data=' + text, '_blank');
var t = setInterval(() => {
if (w.closed) {
clearInterval(t);
resolve(true);
}
}, 100);
})
}
var list = ['text1', 'text2', 'text3'];
for (var i = 0; i < list.length; i++) {
await tempWindow(list[i]);//Each loop iteration must wait for each window to close
}
make sure loop code is inside async function like that
async testFunction(){
var list = ['text1', 'text2', 'text3'];
for (var i = 0; i < list.length; i++) {
await tempWindow(list[i]);//Each loop iteration must wait for each window to close
}
}
call function like this testFunction()

Dom element infinitely incrementing

I'm in my first steps of creating an auto aim system for the enemy bot but I can't even seem to get him to shoot properly.
I create a div element, and move it in a direction. This happens every 4 seconds. I delete the div before the next one gets created. This works. But somehow it creates more and more elements over time and soon turns into a massive amount of divs all flying in the same direction.
** make the bullet here **
function makeBullet() {
if (player.enemy) {
if (player.enemyBullet.bulletInterval == true) {
console.log("working");
player.enemyBullet.bullet = document.createElement('div');
player.enemyBullet.bullet.className = 'bullet';
gameArea.appendChild(player.enemyBullet.bullet);
player.enemyBullet.bullet.x = player.enemy.x;
player.enemyBullet.bullet.y = player.enemy.y;
player.enemyBullet.bullet.style.left = player.enemyBullet.bullet.x + 'px';
player.enemyBullet.bullet.style.top = player.enemyBullet.bullet.y + 'px';
player.enemyBullet.bulletInterval = false;
setInterval(function () {
player.enemyBullet.bulletInterval = true;
}, 4000);
}
}
}
** Move Bullet **
function moveBullet() {
let bullets = document.querySelectorAll('.bullet');
bullets.forEach(function (item) {
item.x += 3;
item.y -= 3;
item.style.left = item.x + 'px';
item.style.top = item.y + 'px';
if(item.y < 200){
item.parentElement.removeChild(item);
player.enemyBullet.bullet = null;
}
})
}
** invoked in request Animation function **
function playGame() {
if (player.inplay) {
moveBomb();
moveBullet();
makeBullet();
window.requestAnimationFrame(playGame);
}
}
** Initiate interval boolean here **
let player = {
enemyBullet: {
bulletInterval: true
}
}
** LINK TO JS FIDDLE FULL PROJECT ** (click here to see what's happening)
https://jsfiddle.net/mugs17/j7f12a0n/
You are using setInterval like set timeout. However setInterval does not only execute one time. Once you've called setInterval the first time, calling it again makes a new different interval that also executes every 4 seconds.
So each time your function gets invoked its creating a new Interval which is why your div elements are increasing as time goes on
Instead wrap the entire create bullet code inside setInterval and make it execute only once by setting a boolean conditional and then immediately changing that conditional to false. Like this:
if (player.enemy) {
if (player.enemyBullet.bulletInterval == true) {
player.enemyBullet.bulletInterval = false;
console.log("working");
setInterval(function () {
player.enemyBullet.bullet = document.createElement('div');
player.enemyBullet.bullet.className = 'bullet';
gameArea.appendChild(player.enemyBullet.bullet);
player.enemyBullet.bullet.x = player.enemy.x;
player.enemyBullet.bullet.y = player.enemy.y;
player.enemyBullet.bullet.style.left = player.enemyBullet.bullet.x + 'px';
player.enemyBullet.bullet.style.top = player.enemyBullet.bullet.y + 'px';
}, 4000);
}
}
}

How to unsubscribe from all the Youtube channels at once?

I have subscribed to more than 300 Youtube channels in past 10 years, and now I have to clean my Youtube, unsubscribing all one by one will take some time, is there a way to unsubscribe all the cannels at once?
Step 1: Go to https://www.youtube.com/feed/channels and scroll to the bottom of the page to populate all items to the screen.
Step 2: Right-click anywhere on the page and click "Inspect Element" (or just "Inspect"), then click "Console", then copy–paste the below script, then hit return.
Step 3:
var i = 0;
var myVar = setInterval(myTimer, 3000);
function myTimer () {
var els = document.getElementById("grid-container").getElementsByClassName("ytd-expanded-shelf-contents-renderer");
if (i < els.length) {
els[i].querySelector("[aria-label^='Unsubscribe from']").click();
setTimeout(function () {
var unSubBtn = document.getElementById("confirm-button").click();
}, 2000);
setTimeout(function () {
els[i].parentNode.removeChild(els[i]);
}, 2000);
}
i++;
console.log(i + " unsubscribed by YOGIE");
console.log(els.length + " remaining");
}
Step 4: Sit back and watch the magic!
Enjoy!!
NOTE: If the script stops somewhere, please refresh the page and follow all four steps again.
Updating the answer provided by everyone else (as the latest update did not work for me):
var i = 0;
var count = document.querySelectorAll("ytd-channel-renderer:not(.ytd-item-section-renderer)").length;
myTimer();
function myTimer () {
if (count == 0) return;
el = document.querySelector('.ytd-subscribe-button-renderer');
el.click();
setTimeout(function () {
var unSubBtn = document.getElementById("confirm-button").click();
i++;
count--;
console.log(i + " unsubscribed");
console.log(count + " remaining");
setTimeout(function () {
el = document.querySelector("ytd-channel-renderer");
el.parentNode.removeChild(el);
myTimer();
}, 250);
}, 250);
}
For me this did the trick.
Youtube Channel Unsubscriber (Works April-2020)
Access the link : https://www.youtube.com/feed/channels
Press F12
Insert the code below in your console
function youtubeUnsubscriber() {
var count = document.querySelectorAll("ytd-channel-renderer:not(.ytd-item-section-renderer)").length;
var randomDelay = 500;
if(count == 0) return false;
function unsubscribeVisible(randomDelay) {
if (count == 0) {
window.scrollTo(0,document.body.scrollHeight);
setTimeout(function() {
youtubeUnsubscriber();
}, 10000)
}
unsubscribeButton = document.querySelector('.ytd-subscribe-button-renderer');
unsubscribeButton.click();
setTimeout(function () {
document.getElementById("confirm-button").click()
count--;
console.log("Remaining: ", count);
setTimeout(function () {
unsubscribedElement = document.querySelector("ytd-channel-renderer");
unsubscribedElement.parentNode.removeChild(unsubscribedElement);
unsubscribeVisible(randomDelay)
}, randomDelay);
}, randomDelay);
}
unsubscribeVisible(randomDelay);
}
youtubeUnsubscriber();
References
https://github.com/vinnyfs89/youtube-unsubscriber
This is a little addition to the best answer:
You can also use jscompress[dot]com to compress the script, then add javascript: at the beginning of the script, and add it to your bookmarks — you can run it from there — just in case you're not comfortable using console or something like that.
Most effective values:
(copy all above this, including the last)
var i = 0;
var myVar = setInterval(myTimer, 200);
function myTimer () {
var els = document.getElementById("grid-container").getElementsByClassName("ytd-expanded-shelf-contents-renderer");
if (i < els.length) {
els[i].querySelector('[aria-label="Unsubscribe from this channel."]').click();
setTimeout(function () {
var unSubBtn = document.getElementById("confirm-button").click();
}, 500);
setTimeout(function () {
els[i].parentNode.removeChild(els[i]);
}, 1000);
}
i++;
console.log(i + " unsubscribed by YOGIE");
console.log(els.length + " remaining");
}
Updating MordorSlave answer. Just did it a moment ago.
Go to https://www.youtube.com/feed/channels and copy/paste the following in the console:
var i = 0;
var myVar = setInterval(myTimer, 200);
function myTimer() {
var els = document.getElementById("contents").getElementsByClassName("ytd-subscribe-button-renderer");
if (i < els.length) {
els[i].querySelector('.ytd-subscribe-button-renderer').click();
setTimeout(function() {
var unSubBtn = document.getElementById("confirm-button").click();
}, 500);
setTimeout(function() {
els[i].parentNode.removeChild(els[i]);
}, 1000);
}
i++;
console.log(i + " unsubscribed");
console.log(els.length + " remaining");
}
https://gist.github.com/itsazzad/c1d86c5db86258ca129554a7b9ed92a7
Use the DELAY const wisely; consider your net speed.
// Go to the following link in your YouTube: https://www.youtube.com/feed/channels
// Scroll the page all the way down until you reach the very last subscribed channel in your list
const DELAY = 100;
const delay = ms => new Promise(res => setTimeout(res, ms));
const list = document.querySelectorAll("#grid-container > ytd-channel-renderer");
for (const sub of list) {
await delay(DELAY);
sub.querySelector("#subscribe-button > ytd-subscribe-button-renderer > paper-button").click();
await delay(DELAY);
document.querySelector("#confirm-button > a").addEventListener('click', async event => {
await delay(DELAY);
console.log(sub.querySelector("#text").innerText);
await delay(DELAY);
});
await delay(DELAY);
document.querySelector("#confirm-button > a").click()
await delay(DELAY);
}
Go to https://www.youtube.com/feed/channels.
Scroll all the way down till you see the last subscribed channel.
Open the javascript console, paste the following code and hit enter
let btns = document.querySelectorAll('paper-button > yt-formatted-string');
for (let i = 0; i < btns.length; i += 1) {
if (btns[i].innerText.toLowerCase() === 'subscribed') {
btns[i].click();
document.getElementById('confirm-button').click();
}
}
Note: For me this method worked on Firefox. Chrome was giving warnings and the page became unresponsive. Worked on Oct 20th 2020 for an account with 956 subscribed channels.
Hmm, wish I'd googled before rolling out my own. I had some fun with async and await with this. The screen does some ugly flashing while it's trying to unsubscribe stuff, but this does the job pretty well.
One prerequisite for this script to catch all channels in one go is to "exhaust" the scroller in the page ie., keep scrolling until you reach the end of your channel list. As others have stated, head on over to YouTube Channels, open the developer console and paste the script that follows.
I've commented in relevant parts, in case this ends up becoming a learning experience for someone ;)
/**
* Youtube bulk unsubsribe fn.
* Wrapping this in an IIFE for browser compatibility.
*/
(async function iife() {
// This is the time delay after which the "unsubscribe" button is "clicked"; Tweak to your liking!
var UNSUBSCRIBE_DELAY_TIME = 2000
/**
* Delay runner. Wraps `setTimeout` so it can be `await`ed on.
* #param {Function} fn
* #param {number} delay
*/
var runAfterDelay = (fn, delay) => new Promise((resolve, reject) => {
setTimeout(() => {
fn()
resolve()
}, delay)
})
// Get the channel list; this can be considered a row in the page.
var channels = Array.from(document.getElementsByTagName(`ytd-channel-renderer`))
console.log(`${channels.length} channels found.`)
var ctr = 0
for (const channel of channels) {
// Get the subsribe button and trigger a "click"
channel.querySelector(`[aria-label^='Unsubscribe from']`).click()
await runAfterDelay(() => {
// Get the dialog container...
document.getElementsByTagName(`yt-confirm-dialog-renderer`)[0]
// and find the confirm button...
.querySelector(`#confirm-button`)
// and "trigger" the click!
.click()
console.log(`Unsubsribed ${ctr + 1}/${channels.length}`)
ctr++
}, UNSUBSCRIBE_DELAY_TIME)
}
})()
If someone is looking for a working solution, the following script worked for me:
Go to https://www.youtube.com/subscription_manager and run
$$('.yt-uix-button-subscribed-branded').forEach(function(el) { el.click(); $$('.overlay-confirmation-unsubscribe-button').forEach(function(el) { el.click(); }); console.log('Bye YouTube'); });
Ref: https://www.reddit.com/r/youtube/comments/ad3jv5/mass_unsubscribe_script/
My solution, most up to date i think, but things always changing...
var unsubBtns = document.querySelectorAll(' div:nth-child(2) > div:nth-child(2) > div:nth-child(2) > ytd-subscribe-button-renderer:nth-child(1) > paper-button:nth-child(1)');
var i = 0;
var interV = setInterval(function(){
unsubBtns[i].click();
i++;
document.querySelector('yt-formatted-string.style-blue-text').click()
}, 1000);
Extending on Jani's answer, this one has a DOM progress counter. Absolutely no jQuery.
(function() {
var i = 0;
var ytdElem = document.querySelector("ytd-page-manager ytd-browse.ytd-page-manager");
ytdElem.innerHTML = '<div style="font: 11pt arial; background: yellow; color: white" id="ytdjsds"></div>' + ytdElem.innerHTML;
var element = document.getElementById("ytdjsds");
var count = document.querySelectorAll("ytd-channel-renderer:not(.ytd-item-section-renderer)").length;
if (count == 0) {
element.innerHTML = "No subscriptions were found on your account.";
return;
}
element.innerHTML = `Deleting subscription 1 of ${count}`;
function myTimer() {
if (count == 0) {
element.innerHTML = `Successfully deleted subscriptions`;
return;
}
element.innerHTML = `Deleting subscription ${i + 1} of ${count}`;
el = document.querySelector('.ytd-subscribe-button-renderer');
el.click();
document.getElementById("confirm-button").style.display = "none";
setTimeout(function() {
var unSubBtn = document.getElementById("confirm-button").click();
i++;
setTimeout(function() {
el = document.querySelector("ytd-channel-renderer");
el.parentNode.removeChild(el);
myTimer();
}, 250);
}, 250);
}
myTimer();
})();
as of October 2021
from this page https://www.youtube.com/feed/channels
var list = $$('yt-formatted-string.ytd-subscribe-button-renderer')
function foo($$) {
if (list.length === 0) return
var el = list.pop()
el.click()
setTimeout(_=>{
var cancel = $$('yt-formatted-string.yt-button-renderer')[1]
cancel.click()
console.log('done')
setTimeout(_=>{foo($$)},100)
}, 100)
}
foo($$)

JQuery Auto Click

I have a problem, I have 3 button lets say it's called #pos1, #pos2 and #pos3.
I want to makes it automatically click #pos1 button in 2 seconds, after that click the #pos2 after another 2 seconds, and #pos3 after another 2 seconds,
after that back to the #pos1 in another 2 seconds and so on via jQuery.
HTML
<button id="pos1">Pos1</button>
<button id="pos2">Pos2</button>
<button id="pos3">Pos3</button>
Anyone can help me please?
Try
$(function() {
var timeout;
var count = $('button[id^=pos]').length;
$('button[id^=pos]').click(function() {
var $this = $(this);
var id = $this.attr('id');
var next = parseInt(id.substring(4), 10) + 1;
if( next >= count ){
next = 1
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
$('#pos' + next).trigger('click');
}, 2000);
})
timeout = setTimeout(function() {
$('#pos1').trigger('click');
}, 2000);
})
var posArray = ["#pos1", "#pos2", "#pos3"];
var counter = 0;
setInterval(function() {
$(posArray[counter]).triggerHandler('click');
counter = ((counter<2) ? counter+1 : 0);
}, 2000);
That should do the trick, though you did not mention when you want it to stop running.
Well I don't know what you already have but technically it could be done via triggerHandler()
var currentPos = 1,
posCount = 3;
autoclick = function() {
$('#pos'+currentPos).triggerHandler('click');
currentPos++;
if(currentPos > posCount) { currentPos = 1; }
};
window.setInterval(autoclick,2000);
If I have understood you question right, you need to perform click in a continuous loop in the order pos1>pos2>pos3>pos1>pos2 and so on. If this is what you want, you can use jQuery window.setTimeout for this. Code will be something like this:
window.setTimeout(performClick, 2000);
var nextClick = 1;
function performClick() {
if(nextClick == 1)
{
$("#pos1").trigger("click");
nextClick = 2;
}
else if(nextClick==2)
{
$("#pos2").trigger("click");
nextClick = 3;
}
else if(nextClick == 3)
{
$("#pos3").trigger("click");
nextClick = 1;
}
window.setTimeout(performClick, 2000);
}
This is quite buggy but will solve your problem.
using setInterval()
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
var tempArray = ["pos1", "pos2", "pos3"]; //create an array to loop through
var arrayCounter = 0;
setInterval(function() {
$('#' + tempArray[arrayCounter ]).trigger('click');
arrayCounter = arrayCounter <2 ? arrayCounter +1 : 0;
}, 2000);
fiddle here
check your console for fiddle example

Categories

Resources