JavaScript / jQuery or something to change text every some seconds - javascript

I need JavaScript or jQuery something to change text every few seconds... without the user doing anything.
Example:
"Welcome" changes to "Salmat datang" changes to "Namaste", etc. after 3 seconds and loops back.

As others have said, setInterval is your friend:
var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 1000);
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) {
counter = 0;
// clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle
}
}
<div id="changeText"></div>

You may take a look at the setInterval method. For example:
window.setInterval(function() {
// this will execute on every 5 seconds
}, 5000);

You can use setInterval to call a function repeatedly. In the function you can change the required text.
The list of texts to change between could be stored in an array, and each time the function is called you can update a variable to contain the current index being used. The value can loop round to 0 when it reaches the end of the array.
See this fiddle for an example.

setInterval(function(){
alert('hello, do you have a beer?');
}, 1000);
where 1000 ms = 1 second.

Related

how can I use setInterval when I want to use while in my function?

<body onload="count()">
<p id="li1"></p>
<script>
let li1 = document.getElementById("li1");
let x = 0;
function count() {
while(x<=1000){
li1.innerHTML = x++;
}
}
setInterval(count,10)
</script>
</body>
I tried to write for instead of using while but it does not work either.
I will reformat your original post shortly. Please be careful to format your future questions properly!
You're doing a few things unnecessarily in your supplied code.
Firstly, you don't need to call count() in the body onload. The setInterval will run after DOM load and effectively handle this for you.
Secondly, because you're using setInterval to run count() every 10ms, you don't need any form of loop, whether it be for or while. The setInterval handles your looping (sort of).
Take a look at the following:
// Get the element we want to put the counter inside
let li1 = document.getElementById("li1");
// Init a variable to hold our counter
let x = 0;
// Init a varible to hold our setInterval timer, so we can disable it when conditions are met.
let counterInterval;
//Define our count() function
function count() {
if (x < 1000){
// Set the innerHTML (I'd rather innerText) to x + 1 as long as x is less than 1000
li1.innerHTML = x++;
} else {
// If x is equal to or greater than 1000, clear the timer
clearInterval(counterInterval);
}
}
//Start our interval time to run count() every 10ms and assign it to our counterInterval variable
counterInterval = setInterval(count,10)
<p id="li1"></p>

delay between function in loop jquery

I have a jQuery function that shows modal boxes:
function ShowAnonce(){
...
jQuery(".ShowAnonce").show();
jQuery(".ShowAnonce").animate({opacity: 1},300).delay(1800).animate({opacity: 0},300);
}
And what I want to do is to show this box 10 times with different random intervals. I used a for loop and setTimeout like this:
for(i=0;i<10;i++){
setTimeout(ShowAnonce(),Math.random()*100);
}
but it shows the box 10 times with no delay. What can I do to fix it?
Also, why can't I do the following at the end of ShowAnonce function?
jQuery(".ShowAnonce").hide();
If I do it, it doesn't shows me box because style display:none keeps being assigned.
Math.random() can return value in decimals also like , 0.123. Which the setTimeout() cannot take . Try Math.ceil (Math.random()) this will give you an integer but might give the same value again and again .
I would try (Math.ceil (Math.random()) *10 ).
As an alternative you can use setInterval as below instead of for loop for x number of times:
var x = 0;
var intervalID = setInterval(function () {
ShowAnnounce();
if (++x === 10) {
window.clearInterval(intervalID);
}
}, Math.random()*100);
Another post about each() iteration gave me an answer. So it works for me:
var time = 0;
for(i=0;i<10;i++){
time = time + Math.random() *10000;
setTimeout(ShowAnonce, time);
}

Jquery: Doing an interval, timout, then interval again

I'm trying to do a reveal of a list of elements 1 after another in a setInterval for 5 seconds but after the 7th element, i want to wait for 60 seconds, meaning a timeout and continue the interval.
Following is my code, I can get it done but the problem with this code is that it does the timeout repetatively on every 7th element, however, i'm only looking to do it on the 1st 7th occurance and not on all the 7th element.
$(document).ready(function(){
var index=0;
var firstInterval=setInterval(function(){
if(index==7){
$("#love p:hidden:first").fadeIn(2000);
clearInterval(firstInterval);
index=0;
return;
}else{
$("#love p:hidden:first").fadeIn(2000);
index++;
}
var timeout=setTimeout(function(){
$("#love p:hidden:first").fadeIn(2000);
var secondInterval=setInterval(function(){
$("#love p.2nd_batch:hidden:first").fadeIn(2000);
},5000);
clearTimeout(timeout);
},60000);
},5000);
});
Any help would be greatly appreciated. thanks
Does this work for you? http://jsfiddle.net/301hsmom/3/ (watch the bottom right)
$(document).ready(function() {
var index = 1;
var firstInterval = setInterval(function() {
if (index === 7) {
$("#love p").filter(":hidden").filter(":first").fadeIn(2000);
clearInterval(firstInterval);
index = 1;
var timeout = setTimeout(function() {
$("#love p:hidden:first").fadeIn(2000);
var secondInterval = setInterval(function() {
var elem = $("#love p").filter(":hidden");
if (elem) {
elem.filter(":first").fadeIn(2000);
} else {
clearInterval(secondInterval);
}
}, 5000);
}, 60000);
} else {
$("#love p").filter(":hidden").filter(":first").fadeIn(2000);
index++;
}
}, 5000);
});
First, your var index = 0; and looping until index === 7 will run 8 times, rather than the intended 7. To fix this, change one of them to var index = 1; or index === 6.
Secondly, you create a new timeout every 5 seconds within the firstInterval code. You only want this to happen once the first 7 elements have been shown. This is fixed by moving it inside the if (index === 7) { statement so it will execute once 7 elements have been shown.
Another optimization I have applied is changing $("#love p:hidden:first") to $("#love p").filter(":hidden").filter(":first"). According to http://api.jquery.com/first-selector/:
Because :first is a jQuery extension and not part of the CSS specification, queries using :first cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :first to select elements, first select the elements using a pure CSS selector, then use .filter(":first").
Changing :hidden is for the same reason. http://api.jquery.com/hidden-selector/.
Now everything works up to the first seven elements (assuming you have at least 7 elements, otherwise you will need to check for the existence of the element in the else within firstIndex). Next, we remove clearTimeout(timeout); as timeout's only run once and do not need to be cleared.
The next thing we do, is because we do not know how many elements there are to display after the first 7, we try to find a hidden element (with var elem = $("#love p").filter(":hidden");) and check for it's existence (using if (elem)). If it exists, we get the first one, and fade it in (elem.filter(":first").fadeIn(2000);), otherwise, we stop looping (clearInterval(secondInterval);).

setInterval() change image

The goal: When the page is loaded, display the image andy_black.jpg. After two seconds, change the image source, and the thus image in the browser, to a second image called andy_white.jpg. This will change back and forth every 2 seconds.
I checked out this article:
SetInterval function calls
(I searched other as well, with the tags [javascript] [function] and the word "setinterval", but most were using jQuery and my intention here is not to use any jQuery, it's an experiment in JavaScript after all).
which was quite helpful for before I had read it my code was much longer and the function was not called in the setInterval() function.
So here's some code:
Suggestions?
var i = 1;
function change_pic() {
i + 1;
if (i == 5) {
i = 1;
}
//I suspect the computer will read i as 5 for some
//tiny amount of time before reverting back to 1
//which I suspect could cause a further problem, but
//is it the source of the current issue?
if (i == 1 || i == 2) {
document.getElementById('img_to_flip').src = "https://cdns-images.dzcdn.net/images/artist/5d9e44027cc266260d7bd932d98f739d/500x500.jpg";
} else {
document.getElementById('img_to_flip').src = "https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg";
}
}
var pic_src = setInterval(change_pic, 2000);
<img id="img_to_flip" src="https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg" height="100" width="100" />
You forget to actually reassign the new value to i.
Either use:
i = i + 1;
or
++i;
Also, why count to five when you only have two states? A common paradigm to have an auto-resetting counter is to use modulo arithmetic:
i = (i + 1) % 2;
which guarantees that i will only ever have values of 0 or 1.
FWIW, here's an alternate way of writing the entire feature that'll work for any number of images - just populate the pics array:
(function() { // function expression closure to contain variables
var i = 0;
var pics = ["https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg", "https://cdns-images.dzcdn.net/images/artist/5d9e44027cc266260d7bd932d98f739d/500x500.jpg"];
var el = document.getElementById('img_to_flip'); // el doesn't change
function toggle() {
el.src = pics[i]; // set the image
i = (i + 1) % pics.length; // update the counter
}
setInterval(toggle, 2000);
})(); // invoke the function expression
<img id="img_to_flip" src="https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg" height="100" width="100" />
If you want to avoid the delay in first time setInterval call the function before the setInterval as shown in the top answer:
(function() { // function expression closure to contain variables
var i = 0;
var pics = [ "andy_white.jpg", "andy_black.jpg" ];
var el = document.getElementById('img_to_flip');
function toggle() {
el.src = pics[i]; // set the image
i = (i + 1) % pics.length; // update the counter
}
toggle()
setInterval(toggle, 2000);
})(); // invoke the function expression

jquery create counter with value from div

I am trying to create a script with jquery that pulls a number from a specified div (#counter below) and adds 100 to it every second and updates the number in the div. I've tried a number of things, but nothing with the intended result. Any tips? Here is what I have currently:
<script type="text/javascript">
setInterval("counter()", 1000); // run counter function every second
function counter() {
var count = $("#counter").val(); // get value of counter div
var total = count+100; // add 100 to value of counter div
$("#counter").text(total); // update counter div
}
</script>
<div id="counter">1000</div>
A few changes:
function counter() {
var count = parseInt($('#counter').text(), 10);
$('#counter').text(count + 100);
}
setInterval(counter, 1000);
Don't pass a string to setInterval. Always pass a function.
.val() is only for <input> elements. You need to use .text() (which will return a string), so you need to parse the text into an integer with parseInt(). The 10 tells parseInt to assume base-10.
Edit - adding parseInt like others mentioned.
You're not calling counter() correctly and you should use .html() instead of val() like this:
<script type="text/javascript">
setInterval(counter, 1000); // run counter function every second
function counter() {
var count = $("#counter").html(); // get value of counter div
var total = parseInt(count)+100; // add 100 to value of counter div
$("#counter").text(total); // update counter div
}
</script>
<div id="counter">1000</div>
use
parseint($("#counter").html(), 10) // or ~~$("#counter").html()
and even
$("#counter").html(total)
instead
Try casting count to an integer?
var total = parseInt(count, 10) + 1000;
Should use jquery html() as opposed to val() unless it is a form input.
var count = $('#counter').html();
Also noticed you are not passing the function reference correctly to setInterval()
setInterval(counter, 1000);
Here is the working code: http://jsfiddle.net/FbJPY/3/
The issue is that your interval is not working, as well as you're not parsing a number from the contents of the div.
Fixes:
Interval should reference a function, not a variable, so you can type counter without quotes.
You need to parse the number from the contents of the div.
setInterval(counter, 1000); // run counter function every second
function counter() {
var count = parseInt($("#counter").text(), 10); // get value of counter div
var total = count + 100; // add 100 to value of counter div
$("#counter").text(total); // update counter div
}

Categories

Resources