Automatically Change Individual Table Data Using Javascript - javascript

I'm trying to mimic the look of a stock-exchange board, but can't seem to automatically change text without stopping another.
I've tried
var text = ["2.0%", "1.7%", "1.9%", "1.8%", "1.9%"];
var counter = 0;
var elem = document.getElementById("n1");
var inst = setInterval (change, 1000);
function change () {
elem.innerHTML = text[counter];
counter++;
var content = document.getElementById("n1");
if (counter >= text.length) {
counter = 0;
}
}
var text = ["-12.0%", "-13.7%", "-13.9%", "-12.8%", "-13.9%"];
var counter = 0;
var elem = document.getElementById("n2");
var inst = setInterval (change, 1000);
function change () {
elem.innerHTML = text[counter];
counter++;
var content = document.getElementById("n2");
if (counter >= text.length) {
counter = 0;
}
}
To no avail.

You can't have two different functions with the same name. One will override the other.
I created a single function that accomplishes your goals by passing in the target element and the data as arguments.
function change(elem, data) {
let counter = 0;
setInterval(function() {
elem.innerHTML = data[counter];
counter++;
if (counter >= data.length) {
counter = 0;
}
}, 1000);
}
change(document.getElementById("n1"), ["2.0%", "1.7%", "1.9%", "1.8%", "1.9%"]);
change(document.getElementById("n2"), ["12.0%", "2.7%", "3.9%", "4.8%", "5.9%"]);
<div id="n1"></div>
<div id="n2"></div>

Related

How to Create a Random Text Generator with Countdown Timer in Javascript?

So, I'm trying to create a random text generator in Javascript using Math.floor and Math.random which I combine with countdown timers using Javascript as well. However, the result after the countdown value has been <= 0 does not appear random text that I have made in the function.
In fact, it appears undefined. How's the solution? The script I created is below.
<button id="btn" style="background-color:red;width:30px;height:30px;"></button>
<script>
var timer = 5;
var id;
function create_random_string(string_length){
var random_string = 'X-';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
for (var i, i=0; i < string_length; i++){
random_string += characters.charAt(Math.floor(Math.random() * characters.length))
}
}
function starButton() {
this.style.display = 'none';
id = setInterval(function () {
timer--;
if (timer <= 0) {
clearInterval(id);
document.getElementById("script").innerHTML = create_random_string(5);
} else {
document.getElementById("script").innerHTML = timer + " seconds to get Code";
} }, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = starButton;
</script>
<div id="script"></div>
You were not returning anything from your function. If you don't return function value how it will get it! Check this now.
var timer = 5;
var id;
function create_random_string(string_length){
debugger;
var random_string = 'X-';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
for (var i, i=0; i < string_length; i++){
random_string += characters.charAt(Math.floor(Math.random() * characters.length))
}
return random_string;
}
function starButton() {
this.style.display = 'none';
id = setInterval(function () {
timer--;
if (timer <= 0) {
clearInterval(id);
document.getElementById("script").innerHTML = create_random_string(5);
} else {
document.getElementById("script").innerHTML = timer + " seconds to get Code";
} }, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = starButton;
<button id="btn" style="background-color:red;width:30px;height:30px;"></button>
<div id="script"></div>

Start setInterval again after clicking on button

i started js a few days ago and made a slider that changes the images when the button is clicked and a timer that changes images automatically every 5 sec. But when i clicked the buttons the timer didnt reset. I used clearInterval to stop the timer but i dont know how to call it to restart it. Here is my Js code.
//progression bar
var width = 1;
//the images
const images = [
"https://www.travelercar.com/wp-content/uploads/2016/04/4a36e314016aa914f203ea6b7d579dc6_large.jpeg",
"https://lemag.nikonclub.fr/wp-content/uploads/2017/07/08.jpg",
"https://www.yourvalleynews.co.uk/wp-content/uploads/2018/03/pic-outside-1080x675.jpg",
];
//the buttons
const suivant = document.getElementById('button1');
const precedent = document.getElementById('button2');
//change image every 5 sec
var counter = 0;
var imageChange;
imageChange = setInterval (function () {
if (counter >= 2 ){
counter -= 2;
document.getElementById("currentImage").src = images[counter];
}
else if (images[0]){
document.getElementById("currentImage").src = images[++counter];
};
}, 5000);
//make buttons work
precedent.onclick = function() {
width = 0;
clearInterval(imageChange);
//I know i have to put something on this line with v imageChange but i dont know what
if (counter <= 0){
counter += 2;
document.getElementById("currentImage").src = images[counter];
}
else{
document.getElementById("currentImage").src = images[--counter];
};
}
suivant.onclick = function() {
width = 0;
clearInterval(imageChange);
//I know i have to put something on this line with imageChange but i dont know what
if (counter >= 2 ){
counter -= 2;
document.getElementById("currentImage").src = images[counter];
}
else{
document.getElementById("currentImage").src = images[++counter];
};
}
//progression bar
function progression(){
var progres = document.getElementById('progression');
var temps = setInterval(frame, 50);
function frame() {
if (width >= 100){
width = 0;
}
else{
width++;
progres.style.width = width + '%';
}
}
}
window.onload = progression;
Feel free to say if have to change some of my ways in the code to make it cleaner. And thanks for taking to help me :)
The main thing is that you have to call setInterval again after you click, in order to restart the interval. Calling clearInterval stops the interval from running.
Here's a way to clean this up a bit:
let counter = 0;
let intervalId;
const getNextImage = (direction) => {
const increment = direction === 'forward' ? 1 : -1;
counter += increment;
if (counter > images.length - 1) {
counter = 0;
}
if (counter < 0) {
counter = images.length - 1;
}
document.getElementById("currentImage").src = images[counter];
};
const startImageLoop = (direction) => {
width = 0;
clearInterval(intervalId);
getNextImage(direction);
intervalId = setInterval(() => {
getNextImage(direction);
}, 5000);
}
precedent.onClick = () => startImageLoop('backward');
suivant.onClick = () => startImageLoop('forward');

Stop Looping Text but still run the effect

Example
var text = 'ENTER...';
var chars = text.split('');
var enter = document.getElementById("enter")
var i = 0;
setInterval (function(){
if (i < chars.length){
enter.innerHTML += chars[i++];
}else{
i = 0;
enter.innerHTML = "";
}
}, 200);
I'm trying to have this typing "enter" effect and I am wondering how to make it only go once. So it will type out "ENTER..." and then stop.
Example
var text = 'ENTER...';
var enter = document.getElementById("enter")
var i = 0;
(function nextLetter() {
enter.innerHTML = text.substr(0, ++i);
if (i < text.length) {
setTimeout(nextLetter, 200);
}
})();
edit: you either have to use setTimeout (one time "sleep"), or remember return value of setInterval and destroy that timer by clearInterval after you don't need it/want it running.
If you use interval, you have to stop the it with clearInterval. Stop it inside the interval function, which is declared as a variable, in the if-statement:
var text = 'ENTER...';
var enter = document.getElementById("enter")
var i = 0;
var interval = setInterval(function() {
enter.innerHTML += text[i];
i += 1;
if(i === text.length) {
clearInterval(interval);
}
}, 200);
JSFiddle
var text = 'ENTER...';
var chars = text.split('');
var enter = document.getElementById("enter")
var i = 0;
var interval = setInterval (function(){
if(i == chars.length) {
clearInterval(interval);
return;
}
if (i < chars.length){
enter.innerHTML += chars[i++];
}else{
i = 0;
enter.innerHTML = "";
}
}, 200);
<div id="enter"></div>

How can I use a default value for this array? The result is not displayed until the first loop

I have this code:
<span id="changeText"></span>
<script type="text/javascript">
var text = ["cool", "awesome", "outstanding"];
var counter = 0;
var elem = document.getElementById("changeText");
var refreshIntervalI = setInterval(change, 2000);
function change()
{
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) { clearInterval(refreshIntervalI); }
}
</script>
The output correctly displays each word after 2000ms, but it also takes 2sec to display the first word. How can I set a default value which will be displayed until the start of the loop?
Thanks in advance :)
Why not just like this
var text = ["cool", "awesome", "outstanding"];
var counter = 1;
var elem = document.getElementById("changeText");
elem.innerHTML = text[0];
var refreshIntervalI = setInterval(change, 2000);
function change()
{
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) { clearInterval(refreshIntervalI); }
}
Set the first value of your array as innerHTML on load and let the counter start at 1 and it should work as intended.
Try to call the function without setInterval() for the first time:
function change() {
...
}
change();

Assign random number to element in javascript but avoid duplicates

Please scroll down to bold text if you want to go straight to the question
I have made a page that consists of a grid of 9 tiles (divs).
Between 1-9 of those tiles could potentially have a slider inside it.
The sliders are all setup via a jQuery each function e.g
_gridSlider.each(function(){
// count slides, setup slider etc
}); // end slider each function
Everything works fine except the sliders all change at the same time and so I want to add some diversity into the start times.
Right now I create a random ID between 1 and X (X being the number of sliders) inside of the each function for each slider like so
_gridSlider.each(function(){
var _sliderID = Math.floor((Math.random() * _numSliders) + 1);
}); // end slider each function
I then start the sliders at a different time based around this ID like so
var _sliderStart = _sliderID + '000';
setTimeout(function() {
startTimer();
}, _sliderStart);
This works fine the only problem is that it is possible for 2 or more sliders to have the same ID, what I need is to assign each slider an ID between 1 and X but make sure that each slider has a different ID.
The end result would be have 1 timer starting at 1 second, another at 2 seconds, another at 3 seconds etc
You can use this function:
function generateId(numSliders) {
var store = generateId._store;
if (!store) {
generateId._store = {};
}
do {
var id = Math.floor(Math.random()*numSliders*1000+1);
} while (store[id])
store[id] = true;
return id;
}
Then you can use generated id as a start time:
var sliderId = generateId(slidersNumber);
var sliderStart = sliderId; // without + '000'
UPD generateId._store keeps used IDs inside itself. In that function store is used as a property of its function, to not add redundant variable to the namespace. You can put it outside of the generateId function. For example:
var store = {};
function generateId(numSliders) {
do {
var id = Math.floor(Math.random()*numSliders*1000+1);
} while (store[id])
return id;
}
But in that case you're polluting the namespace with redundant variable.
store inside of the function is used just to shorten the code a little. If you want you can write:
function generateId(numSliders) {
if (!generateId._store) {
generateId._store = {};
}
do {
var id = Math.floor(Math.random()*numSliders*1000+1);
} while (generateId._store[id])
generateId._store[id] = true;
return id;
}
An example using shuffle.
function createNumberSeries(howMany) {
var result = [];
for (var count = 1; count <= howMany; count += 1) {
result.push(count);
}
return result;
}
function shuffle(obj) {
var i = obj.length;
var rnd, tmp;
while (i) {
rnd = Math.floor(Math.random() * i);
i -= 1;
tmp = obj[i];
obj[i] = obj[rnd];
obj[rnd] = tmp;
}
return obj;
}
function createDivs(ids) {
var length = ids.length;
for (var index = 0; index < length; index += 1) {
var div = document.createElement('div');
div.id = ids[index];
div.className = 'initial';
document.body.appendChild(div);
}
}
function colourDivs(howMany) {
for (var index = 1; index <= howMany; index += 1) {
setTimeout((function(id) {
return function() {
document.getElementById(id).className += ' colorMe';
};
}(index)), index * 1000);
}
}
var numSliders = 10;
var sliderIds = shuffle(createNumberSeries(numSliders));
createDivs(sliderIds);
colourDivs(numSliders);
.initial {
height: 10px;
width: 10px;
border-style: solid;
border-width: 1px;
}
.colorMe {
background-color: blue
}

Categories