Javascript slider through array elements - javascript

Actually next() and previous() buttons are not working like they should be, means if second element is displayed by next button then then after clicking previous button the first element has to be shown but it starts from the end .
One more problem is that after using setTimeout() function, when i click on next it accelerate the speed of timer as it should have same speed for auto play which is given.
var newsArr = ["my name is nouman", "i live in abbottabad", "the breaking news about Pakistan"];
var i = 1;
var x = document.getElementById("demo");
function next() {
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
i++;
} else {
i = 0;
x.innerHTML = newsArr[i];
}
setTimeout(next, 2000);
}
function prev() {
if (i >= 0) {
x.innerHTML = newsArr[i];
i--;
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
}
}
<div class="newsslider">
<p class="text" id="demo">my name is nouman </p>
<button class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
<button class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>

As far as I can guess what you want:
Every time you call the next function a new timeout start. Means that if you click on next for 3 times. You will have 3 timeouts running at the same time. That's way you see it accelerate.
The solution is to clear the running timeout before to set a new one. This way you will always have at most one timeout running.
Also you might wanna first update the index and then adjust it if not valid. Otherwise you might end up in weird situations where you have i > arr.length.
var newsArr = [
"my name is nouman",
"i live in abbottabad",
"the breaking news about Pakistan",
];
var i = 0;
var x = document.getElementById("demo");
var timeoutId;
function next() {
if (timeoutId) {
clearTimeout(timeoutId);
}
i++;
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
} else {
i = 0;
x.innerHTML = newsArr[i];
}
timeoutId = setTimeout(next, 2000);
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = newsArr[i];
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
}
}
<div class="newsslider">
<p class="text" id="demo">my name is nouman </p>
<button class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
<button class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>

Related

How to reset and repeat this function triggered by a button by pressing that button again?

I have a function that chooses a random string from an array and types it in a paragraph. I trigger this function by pressing a button.
var myArray = ['something', 'something else', 'another thing',];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
var i = 0;
var speed = 55;
function typeWriter() {
if (i < rand.length) {
document.getElementById("question").innerHTML += rand.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
<button class="button next" id = "next" onclick="typeWriter()"> Next</button>
<p id="question"></p>
Pressing the "next" button triggers the typeWriter function, which chooses a random string from myArray and begins to type it in the paragraph "question". What I want to happen is, upon pressing "next" again (either while the typing is going on or after the typing is done), the text that has been typed already is deleted and the typeWriter triggers again, choosing another string and typing it in paragraph "question".
You want something like this?
var myArray = ['something', 'something else', 'another thing',];
var speed = 100;
var target = document.getElementById("question");
var char;
var timer;
var sentence;
function type(){
if(char < sentence.length) {
target.innerHTML += sentence.charAt(char++);
} else {
clearInterval(timer);
}
}
function reset() {
clearInterval(timer);
sentence = myArray[Math.floor(Math.random() * myArray.length)];
char = 0;
target.innerHTML = '';
}
function typeWriter() {
reset();
timer = setInterval(type, speed);
}
<button class="button next" id = "next" onclick="typeWriter()"> Next</button>
<p id="question"></p>
The setTimeout you have used implies that each time a character is "pressed", a new timer is started. My approach is to use an interval timer, which is simply writing the next character until the sentence ends or the typewriter is reset. In these two cases, the timer is cleared.
if you are fetching random string then you need to write that code inside your function.
please try below solution.
<button class="button next"
id = "next"
onclick="typeWriter()">
Next
</button>
<p id="question"></p>
<script>
var myArray = ['a', 'b', 'c',];
var i = 0;
var speed = 55;
function typeWriter() {
var rand = myArray[Math.floor(Math.random() * myArray.length)];
if (i < rand.length) {
document.getElementById("question").innerHTML = rand.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
else
{
i--;
}
}
</script>

How to make an auto clicker in JavaScript?

I'm currently making a clicker game and I wanted to know how to make a button that when I click on it, a number slowly goes up with intervals. I don't really know how to do the intervals and I've tried doing loops but loops are instant and have no intervals.
var number = 0;
function increase() {
for (var i = 0; i < 1; i++) {
document.getElementById("number").innerHTML = number += 1
}
}
<button onclick="increase()">
by 1
</button>
<div>
number:
<div id="number">
0
</div>
</div>
Can someone turn this into an auto clicker? as said above, i just want to click on the button once and have the value of the variable "number" go up. Thanks.
Here is mine showing how to
use an interval
use eventListener (unobtrusive coding)
clear the interval
how to increment a number and change speed
how to use data attributes
how to use classes and querySelector
var number = 0,
increment = 1,
speed=1000, // one second
tId;
function inc() {
clearInterval(tId); // stop anything already running
tId = setInterval(function() {
document.getElementById("number").innerHTML = number += increment;
}, speed);
}
function changeSpeed() {
speed = +this.getAttribute("data-speed"); // get attribute and convert to number
inc();
}
window.addEventListener("load", function() { // when page has loaded
document.querySelectorAll(".start").forEach(function(but) {
but.addEventListener("click", function() {
increment = +this.getAttribute("data-inc") ; // get from button and convert to number
inc()
});
});
document.getElementById("stop").addEventListener("click", function() { // when clicking
clearInterval(tId);
});
document.querySelectorAll(".speed").forEach(function(but) {
but.addEventListener("click", changeSpeed);
});
});
<button type="button" class="start" data-inc="1">By 1</button>
<button type="button" class="start" data-inc="10">By 10</button>
<button type="button" class="speed" data-speed="1000">One a sec</button>
<button type="button" class="speed" data-speed="500">Two a sec</button>
<button type="button" id="stop">Stop</button>
<div>
number: <span id="number">0</span>
</div>
function increase() {
setInterval(() => document.getElementById("number").innerHTML = number += 1, 1000)
}
setInterval() will call an anonymous function which increment the number each second (1000 ms) until you call clearInterval()
var number = 0;
function increase () {
number++;
document.getElementById('number').innerHTML = number;
}
Try this out.
I believe the issue is, you're not actually incrementing the variable 'number'. What you're instead doing is setting the content of the element number to number +=1;
So since number is 0;
it will only ever show 1 on the HTML.
If you want the number to increment by one automatically after you've clicked the button once. Create a setInterval.
setInterval(() => {
increase()
}, 5000) // increase every 5 seconds
You can set an interval with setInterval();
var number = 0;
function increase() {
for (var i = 0; i < 1; i++) {
document.getElementById("number").innerHTML = number += 1
}
}
setInterval(increase, 1000);
This should increase the number every second.
If you want to stop it then you can say:
var interval = setInterval(increase, 1000);
clearInterval(interval);
var number = 0;
function increase() {
for (var i = 0; i < 1; i++) {
document.getElementById("number").innerHTML = number += 1
}
}
<button onclick="increase()">
by 1
</button>
<div>
number:
<div id="number">
0
</div>
</div>
var number = 0,
increment = 1,
speed=1000, // one second
tId;
function inc() {
clearInterval(tId); // stop anything already running
tId = setInterval(function() {
document.getElementById("number").innerHTML = number += increment;
}, speed);
}
function changeSpeed() {
speed = +this.getAttribute("data-speed"); // get attribute and convert to number
inc();
}
window.addEventListener("load", function() { // when page has loaded
document.querySelectorAll(".start").forEach(function(but) {
but.addEventListener("click", function() {
increment = +this.getAttribute("data-inc") ; // get from button and convert to number
inc()
});
});
document.getElementById("stop").addEventListener("click", function() { // when clicking
clearInterval(tId);
});
document.querySelectorAll(".speed").forEach(function(but) {
but.addEventListener("click", changeSpeed);
});
});
<button type="button" class="start" data-inc="1">By 1</button>
<button type="button" class="start" data-inc="10">By 10</button>
<button type="button" class="speed" data-speed="1000">One a sec</button>
<button type="button" class="speed" data-speed="500">Two a sec</button>
<button type="button" id="stop">Stop</button>
<div>
number: <span id="number">0</span>
</div>
You can use setInterval(function(){ /* do something every 3 seconds */ }, 3000);
You can call the function in the interval parameter or write the code inside.
You can look at these examples.

Creating a stopwatch which counts down, Initial value from input box

I seem to only advance one digit upon button click and then it stops because the countdown is reverting to the initial value from the input box. I want an initial value entered into the input field, then used as the starting time for the countdown, which will continue until 0.
I'm quite stuck. Is there a solution?
function startButton() {
//--inputValue
var d = document.getElementById("inputValue").value;
if (d != 0) {
--d;
document.getElementById("demo").innerHTML = d;
document.getElementById("omed").innerHTML = "Thank you";
}
else
{
document.getElementById("omed").innerHTML = "Please enter your time";
}
}
<p>Stopwatch </p>
<input type = "number" id = "inputValue"> minutes</input>
<br><br>
<button onClick= "setInterval(startButton(), 1000)">Start counter!
</button>
<button onClick="clearInterval(myTimer)">Pause counter!
</button>
<p id = "demo"></p>
<br>
<p id = "omed">Enter countdown length</p>
What you want to do is to set a variable that contains a timer.
var myTimer = setInterval(function() { /* your action */ }, 60000 );
This will set a timer that fires every 1 minute the "your action" part. As you're using a variable you know how to access the timer and can stop/start it whenever you want.
Now in there we can put your code to update the HTML-element as:
document.getElementById("demo").innerHTML = --d;
The code will be:
var myTimer = setInterval(function() {
document.getElementById("demo").innerHTML = --d;
}, 60000);
You can now stop the timer by calling: clearInterval(myTimer) anywhere you want. So you can still use that in your onClick.
The problem in the above example is that now it will count down even when it hits 0. So you want to stop it automatically as soon as it hits 0.
This can be done by checking on the variable:
if (d !== 0) {
document.getElementById("demo").innerHTML = --d;
}else {
clearInterval(myTimer); // clear the timer when it hits 0 to make sure it'll not go under 0
}
I have added some feedback in the code as well. But it's easy to read: If it's more then 0 then do: d - 1. If it's 0 then stop the timer. You could also put in the else { } a message that the timer is finished.
I changed a few things with the above information in your code:
var myTimer = null;
function startButton() {
clearInterval(myTimer); // Clear the interval so it restarts when reclicking
var d = document.getElementById("inputValue").value;
if (d !== 0) {
document.getElementById("demo").innerHTML = d; // Set info ready so user knows countdown started.
myTimer = setInterval(function() {
if (d !== 0) {
document.getElementById("demo").innerHTML = --d;
}else {
clearInterval(myTimer); // clear the timer when it hits 0 to make sure it'll not go under 0
}
}, 60000);
}
else
{
document.getElementById("omed").innerHTML = "Please enter your time";
myTimer.clearInterval();
}
}
<p>Stopwatch</p>
<input type="number" id="inputValue"> minutes </input>
<br><br>
<button onClick="startButton()">Start counter!
</button>
<button onClick="clearInterval(myTimer)">Pause counter!
</button>
<p id = "demo"></p>
<br>
<p id = "omed">Enter countdown length</p>
Tip: For testing purpose it could be easier to use seconds (1000 instead of 60000) in the interval.
I have modified your code. It seems what you are looking for.
var d = 0;
function setTime(){
d = document.getElementById("inputValue").value;
}
function stopwatch() {
d--;
document.getElementById("demo").innerHTML = d;
document.getElementById("omed").innerHTML = "Thank you";
startButton()
}
var myTimer;
function startButton() {
if (d != 0) {
myTimer = setTimeout(stopwatch, 1000);
}
else
{
document.getElementById("inputValue").value="";
document.getElementById("omed").innerHTML = "Please enter your time";
}
}
<input type = "number" id = "inputValue" onchange="setTime()"> minutes</input>
<br><br>
<button onClick= "startButton()">Start counter!
</button>
<button onClick="clearInterval(myTimer)">Pause counter!
</button>
<p id = "demo"></p>
<br>
<p id = "omed">Enter countdown length</p>

Javascript counter speeds up after the second button click

I have a counter which is activated once startnew button is clicked:
<button id="startnew" onclick="counter()">Start new Game</button>
var i = 0;
function counter() {
var execution = setInterval(function(){
active()
}, 1000);
function active() {
i++;
document.getElementById("timer").innerHTML = i;
}
}
The problem comes when I click on the startnew button for the second time, where counter starts to speed up as an inner variable stays the same.
I have tried adding additional if clauses in different parts of a code which would check if a button was already clicked but had no success so far.
How can I reset an inner variable once the same button was clicked for a second time?
You are creating a new setInterval everytime you click the button.
Call clearInterval(execution) before setInterval and make var execution global. Also Declare your variable i inside the function counter.
var execution;
function counter() {
var i = 0;
clearInterval(execution);
execution = setInterval(function() {
active()
}, 1000);
function active() {
i++;
document.getElementById("timer").innerHTML = i;
}
}
<button id="startnew" onclick="counter()">Start new Game</button>
<br>
<span id="timer"></span>
I hope i understood your Requirement...
Make the variable execution in Global Scope
var i = 0;
var execution;
function counter() {
if (i === 0) {
execution = setInterval(function() {
active()
}, 1000);
} else {
clearInterval(execution);
i = 0;
document.getElementById("timer").innerHTML = '';
}
function active() {
i++;
document.getElementById("timer").innerHTML = i;
}
}
<button id="startnew" onclick="counter()">Start new Game</button>
<span id='timer'></span>

Trying to make automated traffic lights

Hi Im trying to make a set of automated traffic lights but I can't get them to stop running. I have tried using window.clearInterval() but it won't work. Im doing this for my controlled assessment for my GCSE. I really don't know why this won't work so any help would be great. Thanks.
var asset = [
"redyellow.png",
"green.png",
"yellow.png",
"red.png"
];
var counter = 0;
function changeLights() {
if (counter == asset.length) counter = 0;
var image = document.getElementById('redImg');
image.src=asset[counter];
counter = counter + 1;
}
var toggle = 1
function timer() {
if (toggle === 1) {
var on = setInterval(changeLights,5000)
}
else {
window.clearInterval()
}
}
function stopTimer() {
toggle = toggle + 1
}
<!DOCTYPE html>
<html>
<body>
<h1>Traffic Lights</h1>
<img id="redImg" src="red.png" alt="Red traffic light" />
<p>
<button type="button" onclick="timer()">Start Lights</button>
<button type="button" onclick="stopTimer()">Stop Lights</button>
</p>
</body>
</html>
Try making the interval a global variable. Also you need to call self.clearInterval(interval). For example:
var interval;
function timer() {
interval = self.setInterval(changeLights, 5000);
}
function stopTimer() {
self.clearInterval(interval);
}
In your case:
var asset = [
"redyellow.png",
"green.png",
"yellow.png",
"red.png"
];
var counter = 0;
var interval = null;
function changeLights() {
if (counter == asset.length) counter = 0;
var image = document.getElementById('redImg');
image.src = asset[counter];
image.alt = asset[counter]; // debug
counter = counter + 1;
}
function timer() {
if (!interval) {
interval = self.setInterval(changeLights, 1000);
}
}
function stopTimer() {
self.clearInterval(interval);
interval = null;
}
<!DOCTYPE html>
<html>
<body>
<h1>Traffic Lights</h1>
<img id="redImg" src="red.png" alt="Red traffic light" />
<p>
<button type="button" onclick="timer()">Start Lights</button>
<button type="button" onclick="stopTimer()">Stop Lights</button>
</p>
</body>
</html>
Note that I changed it in some ways, most notably removing the code having to do with toggle. This version also allows you to start it again without reloading the page, and prevents you from starting multiple intervals, which would require reloading the page to stop.

Categories