Code restart after end - javascript

How can I restart this code every 10-20 sec.I cant seem to figure it out!
This is the code. (I'm still new any help would be great.)
var items = document.getElementsByClassName('btn-primary next-btn slide-transition ');
for (var i = 0; i < items.length; i++) {
items[i].click();
}

Here you are:
window.setInterval(function(){
var items = document.getElementsByClassName('btn-primary next-btn slide-
transition');
for (var i = 0; i < items.length; i++) {
items[i].click();
}
}, 10000);
It sets up your code as a function that is executed every 10000 millliseconds

You could Just refresh the Page too
Var x = 900000;
setTimeout(function(){
window.location.reload(1);
}, x);
Every x millisecond
Careful though; you will lose the current JavaScript variables that didn't get posted to a database

As per your comment, if you want to execute code every refresh then below code will help you.
var timer;
function StartTimer() {
timer = window.setTimeout(function(){
var items = document.getElementsByClassName('btn-primary next-btn slide-
transition');
for (var i = 0; i < items.length; i++) {
items[i].click();
}
},10000);
}
StartTimer();

Related

How to use setInterval() inside for loop

Please find my code below.
for (i= 0; i < region.length; i++) {
point = region[i];
animation = setInterval(function () {
..........
}, 12);
}
I want to execute the codes in setInterval before i value changes from 0 to 1. But currently after all the execution of for loop only, codes in the setInterval method is getting executed. is there any way to achieve my requirement.
Use closure inside for loop:
(function(i) {
setInterval(function() {
console.log("inside setinterval" + i)
}, 10);
})(i)
hope this solves your problem
Async loop you need:
var len = region.length;
var i = 0;
var animate = function(){
setTimeout(function () {
point = region[i];
//do something..........
if (i++ < len) animate();
}, 12);
};
You should use recursion for such requirements. Also, you should use setTimeout as setInterval will run for eternity(till page exists) until you clear it.
var i = 0;
var MAX_COUNT = 10;
function doSomething(str){
console.log(str);
processData();
}
function initSetTimeout(callback){
setTimeout(callback, 1000)
}
function processData(){
if(++i<MAX_COUNT)
initSetTimeout(doSomething.bind(null, i))
}
processData()

Image not changing

Hi I am trying to get an image to blink using the code below by changing the image. Is there something wrong with my "setTimeout"? TIA
var Test = new Array();
Test.length = 2;
for (var i = 0; i < Test.length; i++) {
Test[i] = new Image();
Test[i].src = "images/Image2" + (i+1) + ".png";
}
function ChangeImage() {
for (var i = 0; i < Test.length; i++) {
document.getElementById('Test_Image').src = Test[i].src;
}
setTimeout("ChangeImage()", 1000);
}
ChangeImage();
First.. you complicated yourself with the new Image() part. You could just use Test[i] = "images/Image2" + (i+1) + ".png";
And for your code, firstly you change the images really fast once every 1 second.
It should be something like this:
function ChangeImage() {
for (var i = 0; i < Test.length; i++) {
setTimeout(function(){document.getElementById('Test_Image').src = Test[i];
}, (i+1) *1000);
}
if(play){
setTimeout("ChangeImage()", Test.length * 1000);
}
}
This will not halt the javascript code at any point.
After 1 sec it will put image21, after 2 seconds image21 and it will call itself again and it will start all over again;
I put the variable play so you could stop the animation if you wanted.
setTimeout() is not blocking. That means it only schedules an activity to happen some time in the future and the rest of your Javascript just keeps running. So, you were scheduling Test.length setTimeout() all for the exact same time 1 second from now. Instead, you need to schedule the next image change and then, when that timer fires, you schedule the one after that and so on.
If you just want to cycle through the various images one second apart, you can do this:
function ChangeImage() {
var cntr = 0;
function next() {
if (cntr < Test.length) {
document.getElementById('Test_Image').src = Test[cntr++].src;
// after changing src, schedule next change for 1 second from now
setTimeout(next, 1000);
}
}
// start first iteration
next();
}
ChangeImage();
You may also need to make sure that all your images are properly preloaded so they display immediately when you set their source. There are numerous ways to make sure the preload is done before starting the rotation such as these:
Image preloader javascript that supports events
How do you cache an image in Javascript
Try something like this.
Edit: Accidentally put setTimeout instead of setInterval. Thanks Santi for point that out.
var Test = new Array();
Test.length = 2;
for (var i = 0; i < Test.length; i++) {
Test[i] = new Image();
Test[i].src = "images/Image2" + (i+1) + ".png";
}
var count = 0;
function ChangeImage() {
if (count >= Test.length)
count = 0;
document.getElementById('Test_Image').src = Test[count].src;
count++;
}
setInterval(ChangeImage, 1000);
Your for loop switches the src once and immediately switches it back, so you can't see it change. Try this instead:
var Test = [];
for (var i = 0; i < 2; i++) {
Test.push("images/Image2" + (i+1) + ".png");
};
var x = 0;
document.getElementById('Test_Image').src = Test[x];
(function ChangeImage() {
if(++x >= Test.length) x = 0;
document.getElementById('Test_Image').src = Test[x];
setTimeout(ChangeImage, 1000);
})();
EDIT: As Santi pointed out, my original solution only supported two images, while OP requested to loop through an array.

Javascript keep getting undefined after function - prompt

So I`m working ona simple JS code. We just started to learn about functions.
I need to make a function named "printStars".
I need to take a number from the user and accourding that number print "*".
This is what I did:
<script>
function printStars()
{
var n = Number(prompt("Insert number of stars:","0.."));
for (i = 0; i < n; i++)
{
document.write("*");
}
}
var stars = printStars();
document.write(stars);
</script>
In the end I get my result with a minus of getting "undefined".
I would love to get some help, and an explanation why is keep happening.
Thanks guys!
jsfiddle demo
function printStars(){
var n = prompt("Insert number of stars:","0..");
var stars='';
for (i = 0; i < n; i++){
stars+='*';
}
$('body').html(stars) //jsfiddle does not allow document.write()
//document.write(stars);
}
//call the function
printStars();
You don't need this
document.write(stars);
You just need this:
// This will make you function to be evaluated and
// the code in your function will be executed.
printStars();
function printStars()
{
var n = Number(prompt("Insert number of stars:","0.."));
for (i = 0; i < n; i++)
{
document.write("*");
}
}
printStars();

Loop in javascript to append a series of divs

This is my code, but it does not work.
for (i = 0; i < 5; i++) {
$(function(){
$('.tt'+ [i]).appendTo('.td'+ [i]);
});
}
I want the result:
$('.tt1').appendTo('.td1')
$('.tt2').appendTo('.td2')
$('.tt3').appendTo('.td3')
$('.tt4').appendTo('.td4')
$('.tt5').appendTo('.td5')
Please correct me, thanks you in advance!
You have some syntax errors, try this:
for (var i = 0; i <= 5; i++) {
$('.tt'+ i).appendTo('.td'+ i);
}
As already mentioned: remove the array initialization.
If you want to iterate from 1 to 5 then do so (not var = 0, but var i = 1):
for (var i = 1; i < 6; i++) {
$('.tt'+ i).appendTo('.td'+ i);
}
Also I don't see any sense in wrapping it the appendTo call.
The 1st Thing
You will never jump into the i=5 iteration
$('.tt5').appendTo('.td5')
because your for loop
for (i = 0; i < 5; i++)
ends at i = 5
Change it to
for (i = 1; i <= 5; i++)
It starts at i=1 because your example didn't show a ".tt0"
The 2nd thing
Remote the brackets!
Change
$('.tt'+ [i]).appendTo('.td'+ [i]);
to
$('.tt'+ i).appendTo('.td'+ i);
Otherwise you will create an Array and the JS interpreter performs an unnecessary Array.toString() operation.
The 3rd thing
I think you can remove the surrounding function inside the for loop
$(function(){
...
}
Just use:
for (var i = 1; i <= 5; i++) {
$('.tt'+ i).appendTo('.td'+ i);
}
See Fiddle
http://jsfiddle.net/Spaghettirocker/knkpaczg/1/

Constantly loop a javascript array and display results to div?

I have a bunch of testimonials for my site which are currently on a page and am trying to get a div to display each 1 at an interval of 5 seconds, if the array reaches the last value it should start back to beginning of the array again.
Here is what I have so far...
var testimonial = new Array();
testimonial[1] = "Rugby";
testimonial[2] = "Baseball";
testimonial[3] = "Cricket";
var length = testimonial.length
var i = 1;
setInterval(function() {
while (i <= length) {
$('#testimonials p').html(testimonial[i]);
++i;
if (i == length) {
i == 1;
}
}
}, 5000);
Any help would be great, thanks.
Try
var testimonial = ['Rugby', 'Baseball', 'Cricket'];
var numTestimonials = testimonial.length;
var index = 0;
setInterval(function() {
$('#testimonials p').text(testimonial[index]);
index = (index + 1) % numTestimonials;
}, 5000);
JavaScript arrays are 0-indexed and have handy array literal syntax. Using the modulus operator (%) is an idiomatic way of wrapping a counter back to 0 once it reaches a certain value.
You can try
setInterval(function() {
$('div').html(test[ (i = (i + 1) % length) ]) },
5000);
The function in setInterval is being called every 5 seconds. That means you display the 5 testimonials one after another really quick every 5 seconds instead of displaying them one after the other.
You should do something like:
var testimonial = new Array();
testimonial[1] = "Rugby";
testimonial[2] = "Baseball";
testimonial[3] = "Cricket";
var length = testimonial.length
var i = 0; // arrays start with 0
setInterval(function() {
$('#testimonials p').html(testimonial[i]);
i++;
if (i == length) i = 0;
}, 5000);
Many interesting answers, so one more won't hurt. :-)
You can bundle it all up in an immediately called function expression:
(function() {
var testimonials = ['Rugby', 'Baseball', 'Cricket'];
var i = 0;
setInterval(function() {
$('#testimonials p').text(testimonials[++i % testimonials.length]);
}, 5000);
}());

Categories

Resources