im trying to make a script that picks 1 random class name out of 3
every 1 minute and clicks the button with the chosen class
so far i created the script that clicks on the button:
setTimeout(function () {
$(".btn-danger").trigger("click");
}, 100);
The problem is if i put it in a while(true)
the site stuck and then the browser crashes.
Also im have no idea how to make it to chose random class so i putted in one of them.
Will be glad to get some help here :D
Check out setInterval() to run something over and over. You can generate a random index from 0 to 2 with Math.floor(Math.random() * 3).
For example, you could select a random class name like this:
var classes = ["classA", "classB", "classC"];
function selectRandomArrayElement(array) {
return array[Math.floor(Math.random() * array.length)];
}
var rand = selectRandomArrayElement(classes);
So, putting it all together:
var classes = ["classA", "classB", "classC"];
function selectRandomArrayElement(array) {
return array[Math.floor(Math.random() * array.length)];
}
// click on a the object with a random class name every minute
setInterval(function() {
var rand = selectRandomArrayElement(classes);
$("." + rand).trigger("click");
}, 1000*60);
In Javascript, you can't use while(true) long duration loops like this block the rest of the browser from processing events and thus your the click events you trigger are never processed. Instead, you use timers to do something repeatedly.
You're looking for setInterval instead of setTimeout, which will invoke the callback indefinitely at the interval you specify.
setInterval(function () {
$(".btn-danger").trigger("click");
}, 60000);
Should work for you. while(true) crashes your browser because you're creating an infinite loop that blocks any other code from executing.
setTimeout uses milliseconds and only occurs once. Use setInterval with one second * 60 to get a minute.
var minute = 1000 * 60;
setInterval(function() { $(".btn-danger").trigger("click");
}, minute);
Related
I have been trying to create a function that generates a random number but I want this number to change every 5 minutes. Below is the code that I have tried:
function randNum(){
let randomNumber = Math.floor(Math.random() * 10);
const paragraphNew = document.createElement("p");
const watchNow = document.createTextNode(randomNumber + " are viewing this product now.");
paragraphNew.appendChild(watchNow);
const element1 = document.getElementById("cart-container");
element1.appendChild(paragraphNew);
}
When I try using the setInterval function like this:
let randomNumber = setInterval(Math.floor(Math.random() * 10), 5000);
I always get 1 as a result. I have also tried calling the function like this:
setInterval(randNum, 5000);
The problem is that a new paragraph is getting added everytime, without deleting the last one.
How can I make it work so I can generate the same number that lasts 5 minutes even after I refresh the page?
Ok) so basically when you refresh your page, all the variables and timeouts are reset. What comes to mind - you can store the variable in some sort of storage (ex. - localeStorage) along with creation date, then run your func with timeout like you did, but if you reload the page - look at storage first, and compare datestamp with current date)
Also keep in mind the things #Josh mintioned in his answer
You're returning the interval instead of the value it generates. Try something like this:
let randomNumber = 0;
setInterval(() => {
randomNumber = Math.floor(Math.random() * 10)
}, 5000);
alert(randomNumber)
Now you're updating the random number every 5 minutes. If you want to display the number every 5 minutes, add your log inside the arrow function. Let me know if you have anymore questions!
I missed the refresh the page part of your question. As #Nikita Mazur mentioned, local storage is the best way!
I have this problem that came up and I realized that I don't understand callbacks nearly as good as I should.
The way it's worded makes me think that I need to make it a set interval, but then you see that there is the syntax of "function randomExecution(callback) {}" and that really trips me up.
On top of all of this, this problem really makes me realize how inefficient I am at breaking down a problem into smaller parts. I see the "make sure it's on average about 1~2 times per minute" and I just get lost.
(I get that i can be less than 10 seconds that I have the min set to, but I'm pretty lost here and that was my only solution to make it so it doesn't get called within ten seconds)
What am I doing wrong here?
Also, any advice on how to approach questions like this would be greatly appreciated.
Cheers!
The Problem:
function randomExecution(callback) {
// start an interval that executes `callback()` at random intervals
// make sure it's on average about 1~2 times per minute
// make sure it doesn't execute twice within 10 seconds
}
My attempt:
function randomExecution(callback) {
const min = 10
const max = 120
const random = Math.floor(Math.random() * (max - min + 1) + min)
// callback = console.log('Wait for ' + random + ' seconds')
return random
}
setInterval(console.log(`hi, after ${randomExecution()} seconds`) , randomExecution)
The problem lies in the fact that you use the function SetInterval, which, as the name suggests, is used to call a specified function repeatedly after a fixed interval. A better approach would be to create a recursive loop with SetTimeout, where your code would look like this:
function example() {
console.log('See you soon!')
}
function randomExecution(callback) {
// start an interval that executes `callback()` at random intervals
// make sure it's on average about 1~2 times per minute
// make sure it doesn't execute twice within 10 seconds
const min = 30
const max = 60
var random = Math.floor(Math.random() * (max - min + 1) + min)
setTimeout(function() {
callback();
randomExecution(callback);
}, random * 1000);
}
randomExecution(example)
I have an element #ChatStatus which is constantly changing, and when a change occurs, the element slides in being visible on screen.
What I'm trying to do now is: If there hasn't occurred any changes on this element for the last 5 seconds for example, hide the element back out of the screen. Here's my code:
$('#ChatStatus').on("DOMSubtreeModified",function(){
$('#ChatStatus').animate({'right':'30px'},500);
});
// Now I wanna run this, when the #ChatStatus is innactive, or no changes occurred
// $('#ChatStatus').animate({'right':'-200vw'},500);
Here's the full project where I want to implement this inactivity feature.
https://jsfiddle.net/shuffledPixels/77hb2do0/1/
Here is a very functional way of doing it. As your commenters have mentioned, this really isn't the best way of doing it; but if you want to, it's your code.
shouldRemove = null;
$('#ChatStatus').on("DOMSubtreeModified",function(){
clearTimeout(shouldRemove);
$(this).animate({'right':'30px'},500);
shouldRemove = setTimeout(function () {
$(this).animate({'right':'-200vw'},500);
}.bind(this), 5000);
});
I am not very experienced with JS animation and the like, so I'll leave any question of style and method choice up to you. Aside from that, I would suggest using a global variable holding the time of the last change, and polling at regular intervals to see if that time is more than 5 seconds ago. For example:
var lasttime = none
$('#ChatStatus').change(function () {
lasttime = new Date().getTime() //Set lasttime to the time when the element changed
}
setInterval(function () {
if ((new Date().getTime() - lasttime) > 5000) { //Date().getTime() is in miliseconds,
// so 5000 for five seconds
$('#ChatStatus').animate({'right':'-200vw'},500);
}
}, 1000); // Set 1000 (1 second) lower for more precision at the
// cost of more computational time
I hope this helps!
I have a simple little javascript count up timer on my page that I want to tweak, but really don't know where to begin.
The goal is that instead of it counting straight up in timed intervals is to have it jump randomly upward.
for example, if my timer is showing 100 and is set to increase again in 1 second, instead of it showing 101, I want it to show some random number between 101 & 106.
Any nods in the right direction would be greatly appreciated.
I appreciate the help you guys gave me (posts 1&2) ... but i'm still missing it somehow.
Here is the link to what i currently have... http://jsfiddle.net/FQSAH/19/
As you see it run, it's moving up by 1, but i'm wanting it to move up by a random number between 1&5 each time.
var x = 0;
setTimeout(function() {
// random interval between 1 and 10
var interval = Math.floor((Math.random() * 10) + 1);
x += interval;
}, 1000);
Tweak 10 as large as you want for a higher variability in intervals.
With a setInterval() you could schedule a function to run every second.
To get the random effect working, you could create a function to update a variable using Math.random().
For example:
var value = 0;
function randomize() {
value += (1 + (Math.random() * 5)); //random value between 1 and 5
}
setInterval(randomize, 1000);
base ={time:0};
var loop = 0;
setInterval(function(){
if(base.time === 9000){
move();
base.time = 0;
}
base.time ++;
},1);
Shouldn't the move(); function occur every 9s? I timed it and its much less, why is that?
setInterval will not run every millisecond. There is a minimum possible interval that is longer than that.
If you want something to run in nine seconds, you should use setTimeout() for 9 seconds. Plus your code doesn't reset base.time back to zero so it would only match 9000 once anyway.
If you want it to run every 9 seconds, then you can use setInterval(handler, 9000) or you can use setTimeout(handler, 9000) and then set the next setTimeout in your handler function.
This will execute move() every nine seconds:
var intervalTimer = setInterval(function(){
move();
}, 9000);
Here's a useful article on the topic: http://www.adequatelygood.com/2010/2/Minimum-Timer-Intervals-in-JavaScript.
To reset the time back to 9 seconds when a button is clicked use this code:
var intervalTimer;
function startTimer() {
intervalTimer = setInterval(function(){
move();
}, 9000);
}
function handleClick() {
clearInterval(intervalTimer); // stop currently running interval
startTimer();
}
startTimer();
See it in action here: http://jsfiddle.net/jfriend00/sF2by/.
Intervals are easy as pie!
var move = function(){
alert("move!");
};
setInterval(move, 9000);
See it work here on jsFiddle
You can't count on setInterval actually running every 1 ms. If the CPU is used for another process, it might not run for 1 second. Instead, use one of the following:
function move() {
// Do stuff.
}
// The obvious solution.
// Certain browsers (Chrome) may put the script in "inactive" mode which will
// pause setInterval code. This means move will be run too few times, if you
// actually depend on it being called X times for Y time.
setInterval(move, 9000);
// The other solution.
// Get the delta between each loop and run the move loop as necessary.
// WARNING: This is not efficient, and you should only use this if you have a
// good reason to do so.
// EXTRA WARNING: This code is actually retarded in its current form. It's just
// here to show you how you'd do it. Since you didn't post your
// original problem, it's hard to know what you're really after.
var time = +new Date, frequency = 9000;
setInterval(function () {
var dt = new Date - time;
// Check if we've waited long enough.
if (dt >= frequency) {
// If the process hangs for 20 seconds, this value would be 2. Usually,
// it will be 1.
// Also, Chrome will pause interval counters, so if a tab is inactive,
// this count could be really high when the tab gets focus again.
var times = Math.floor(dt / frequency);
console.log('Moving', times, 'time(s)!');
for (var i = 0; i < times; i++) {
move();
}
// Start counting time from the last update.
time += times * frequency;
}
}, 1); // 1 could probably be much higher here. Depends on your use case.
You wrote in a comment that there is a button which resets the time, and that's why you don't want to just setTimeout for the full delay. Here's how to handle that:
var running;
function start() {
clearInterval(running);
running = clearInterval(function () {
move();
}, 9000);
}
Every time start() is called, the time will be reset to 9 seconds from now, and if 9 seconds elapse, move() will be called and another 9-second interval will start. If you don't actually want it to happen repeatedly, just use setTimeout instead.
The key is using clearInterval (or clearTimeout) to cancel your previous 9-second-delay and start a new one. It is harmless to call clearInterval with a junk value.