how to change image for every 4 seconds in javascript? - javascript

i want to change image i have done code still image is not showing at all. file not found error is showing i want to change image every 4 seconds how can i do that? please help
<html lang="en">
<head>
<title>sliding image</title>
</head>
<body onload="f1()">
<img id="img1" src=""alt="" width="200px">
<script>
let arr=new Array();
function image()
{
let img2=document.getElementById("img1");
x=0;
arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\1200px-Heart_corazon.svg.png"
img2.src=arr[x];
x=1;
arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\alex-haney-AGqzy-Uj3s4-unsplash.jpg"
img2.src=arr[x];
x=2;
arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\mitchell-luo-jz4ca36oJ_M-unsplash.jpg"
img2.src=arr[x];
x=0;
}
function f1()
{
window.setInterval(image,4000);
}
</script>
</body>
</html>

The images have the names 1.jpg, 2.jpg and 3.jpg and are in the same folder with test.html and test.js file. U can switch the timeout in seconds.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="test.js" type="text/javascript" defer></script>
</head>
<body>
<img id="imageSwitcher" src="" alt="">
</body>
</html>
"use strict";
const imageArray = ["1.jpg", "2.jpg", "3.jpg"];
const imageSwitcher = document.getElementById("imageSwitcher");
let timeout = 4;
let i = 0;
setInterval(() => {
imageSwitcher.src=imageArray[i];
console.log(i);
i++;
if (i >= imageArray.length) {
i = 0;
}
}, timeout * 1000);

You have to increment the pointer and reset it like below code.
<script>
var pointer = 0;
var imageArray = [
"C:\Users\SUDARSHAN\Desktop\html_UI\images\1200px-Heart_corazon.svg.png",
"C:\Users\SUDARSHAN\Desktop\html_UI\images\alex-haney-AGqzy-Uj3s4-unsplash.jpg",
"C:\Users\SUDARSHAN\Desktop\html_UI\images\mitchell-luo-jz4ca36oJ_M-unsplash.jpg"
];
function image()
{
let img2 = document.getElementById("img1");
img2.src = imageArray[pointer];
pointer++;
// reset the pointer if hit the max
if (pointer == imageArray.length-1){
pointer = 0;
}
}
function f1()
{
window.setInterval(image,4000);
}
</script>

Related

Undifined error after switching through images in Javascript

I am trying to create a website with one picture in the middle that changes after a given time. However after running through the loop once, no picture is shown for a short while and my console shows:
Shortly after, it switches through the images again. But having the image dissapear for a short while is a no go.
My Javascript looks like this:
var allPictures = new Array();
var index = 0;
allPictures[0] = "imgA.jpg";
allPictures[1] = "imgB.jpg";
allPictures[2] = "imgC.jpg";
addEventListener("load",() => {
setInterval( function() {
changeImage()
}, 500);
});
function changeImage() {
document.getElementById("galleryPicture").src = allPictures[index];
if (index < allPictures.length) {
index += 1;
} else if (index >= allPictures.length) {
index = 0;
}
}
My HTML looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="main.css">
<title>Website</title>
</head>
<body>
<script src="pictureSwapScript.js"></script>
<div class="galleryPicture">
<img id= "galleryPicture" src="imgA.jpg">
</div>
</body>
</html>
The problem is the condition used to increment index, it will get outside the boundaries of the array.
Replace it with
if (index >= allPictures.length - 1) {
index = 0;
} else {
index += 1;
}
There are other minute improvements that can benefit your code, among which the most obvious to me is replacing:
setInterval( function() {
changeImage()
}, 500);
with just
setInterval(changeImage, 500);
Below code solves your usecase.
function changeImage() {
if (index < allPictures.length - 1) {
index += 1;
} else if (index >= allPictures.length - 1) {
index = 0;
}
document.getElementById("galleryPicture").src = allPictures[index];
}
You were trying to compare index value with length, index always starts from 0. Hence you will have to decrease length by 1 because length starts from 1

How to make stop button in Javascript to stop everything

I intended to make a Countdown Time, but I'm getting a problem. I tried a lot but I'm getting nothing. Please help me to get out of this situation.
I want to make a stop button that resets every value of variable and also stops sound when I click on the stop button.
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<!-- <script src="./script.js"></script> -->
<title>Timer</title>
</head>
<body>
<input type="number" id="time-number" placeholder="Enter Seconds" />
<h3>Time Left <span id="time-left"></span></h3>
<button id="start-button">Start</button>
<button id="stop-button">Stop</button>
<script>
document.addEventListener("DOMContentLoaded", () => {
const timeLeftDisplay = document.querySelector("#time-left");
const startButton = document.querySelector("#start-button");
const stopButton = document.querySelector("#stop-button");
var myAudio = new Audio("./sounds.mp3");
function countDown() {
var timeleft = document.getElementById("time-number").value;
console.log(timeleft);
setInterval(function () {
if (timeleft <= 0) {
clearInterval((timeleft = 0));
myAudio.play();
}
timeLeftDisplay.innerHTML = timeleft;
timeleft -= 1;
}, 1000);
}
startButton.addEventListener("click", countDown);
stopButton.addEventListener("click", () => {
myAudio.pause();
});
});
</script>
</body>
</html>
you are not using correctly the clearInterval function, it spects the id of an interval to clear. keeping a variable on top of the function will help you to track the intervals.
added some comments to improve the code
document.addEventListener("DOMContentLoaded", () => {
let intervalId = null;
const timeLeftDisplay = document.querySelector("#time-left");
const startButton = document.querySelector("#start-button");
const stopButton = document.querySelector("#stop-button");
const myAudio = new Audio("./sounds.mp3");
function countDown() {
// clear an old interval just in case the user clicks several times the start button
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
var timeleft = document.getElementById("time-number").value;
// this is to show inmediatly the counter and start counting
timeLeftDisplay.innerHTML = timeleft;
timeleft -= 1;
intervalId = setInterval(function() {
if (timeleft <= 0) {
// here we use the interval Id to clear the interval.
clearInterval(intervalId);
intervalId = null;
myAudio.play();
}
timeLeftDisplay.innerHTML = timeleft;
timeleft -= 1;
}, 1000);
}
startButton.addEventListener("click", countDown);
stopButton.addEventListener("click", () => {
document.getElementById("time-number").value = ""
timeLeftDisplay.innerHTML = ""
myAudio.pause();
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<!-- <script src="./script.js"></script> -->
<title>Timer</title>
</head>
<body>
<input type="number" id="time-number" placeholder="Enter Seconds" />
<h3>Time Left <span id="time-left"></span></h3>
<button id="start-button">Start</button>
<button id="stop-button">Stop</button>
</body>
</html>

How do I print each character of a string but with 1s of delay in JavaScript?

I want to print "Hello World" on the screen but its each character one by one with 1 second delay. I've used setInterval() function but its not working. Why?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
</head>
<body>
<script>
function type(){
var text = "Hello World!";
var i;
var o = "";
for(i = 0;i < text.length;i++){
o += text[i]
document.write(o[i])
}
}
var exe = setInterval(type(), 1000);
</script>
</body>
</html>
There're so many mistakes in your code, I don't know where to start...
Sorry to put it this way, but here's a cleaner version follows your approach, mind the comments:
const text = "Hello World!";
// the timer reference
let timer;
// the current index
let i = 0;
// you don't need a for loop in setInterval, the function itself is aleady called in iterations, just treat it as a loop iteration.
function type() {
// print the current charater with current index
document.write(text[i]);
// increase the index
i++;
// if the index reaches the maximum text length, cease the timer
if(i >= text.length)
clearInterval(timer);
}
// pass in function, instead of calling it
timer = setInterval(type, 1000);
We simply split our string into arrays and, when inserted into the page, delete the first element.
When there are no elements left in our array, we stop the timer.
let str = 'Hello world'.split('');
const interval = setInterval(() => {
document.write(str[0]);
str = str.slice(1);
if (!str.length) {
clearInterval(interval);
}
}, 1000);
I've made few changes with your logic.
type() function will only do char print.
intialize starting position with 0 and text.
when i is same as text.length clearInterval
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
</head>
<body>
<script>
var text = "Hello World!";
var i = 0;
var o = "";
function type() {
o += text[i];
document.write(o[i]);
i++;
if (i == text.length) {
clearInterval(interval);
}
}
var interval = window.setInterval(type, 1000);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
</head>
<body>
<script>
function type(){
var text = "Hello World!";
var o = "";
for(let i = 0;i < text.length;i++){
o += text[i];
setTimeout(()=> document.write(o[i]), i*1000);
}
}
type();
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
</head>
<body>
<script>
var i = 0
var o = "";
var text = "Hello World!";
function type(){
if(i < text.length){
o += text[i]
document.write(o[i])
i++
setTimeout(type, 1000)
}
}
setTimeout(type, 1000)
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
</head>
<body>
</body>
<script>
var i=0;
var text = "Hello World!";
var exe = setInterval(function (){if (i<text.length)
document.write(text[i])
i++;}, 1000);
</script>
</html>
Something like this perhaps?
const word = "Hello World";
function printWord(str) {
if (typeof str === "string") {
let curIndex = 0;
const interval = setInterval(() => {
if (curIndex < str.length) {
console.log(str[curIndex]);
curIndex++;
} else {
clearInterval(interval);
}
}, 1000);
}
}
printWord(word);
var interval = null
function type(){
var text = "Hello World!";
var i = 0;
interval = setInterval( () => {
if( i === text.length -1) {
clearInterval(interval);
}
document.write(text[i]);
console.log(text[i++]);
}, 1000)
}
type()
We can use the concept of a closure and maintain the index of the character to be printed as a closure variable.
Each time the interval callback function is executed, the index is incremented and the inner function takes the current value of the index from the lexical scope.
Then once the length of the text is equal to the index, the interval is cleared:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
</head>
<body>
<script>
function type(text, idx) {
document.write(text[idx]);
}
function start() {
//The index to keep track of and increment from the timer
let idx = 0;
//The text to iterate
const text = "Hello World!";
//Set up the interval with a callback and form a closure
const id = setInterval(() => {
//Refers to the text and idx from the lexical scope
type(text, idx++);
//Once the index has reached the length of the text
if (idx === text.length) {
//clear the interval id
clearInterval(id);
}
}, 1000);
}
//Invoke the main function
start();
</script>
</body>
</html>

User selects another tab, the page title changes to a different title every 8 seconds

I am trying to change the title of a tab based on a timer.
I have found an example online but can't get it to work, also i don't know if it supports multiple page titles.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.
min.js">
</script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="Script.js"></script>
</head>
<body>
</body>
</html>
$(function() {
var origTitle, animatedTitle, timer;
function animateTitle(newTitle) {
var currentState = false;
origTitle = document.title; // save original title
animatedTitle = "Hey There! " + origTitle;
timer = setInterval(startAnimation, 20);
function startAnimation() {
// animate between the original and the new title
document.title = currentState ? origTitle : animatedTitle;
currentState = !currentState;
}
}
Here's an example that changes the title every 8 seconds.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<script>
var counter = 0;
setInterval( function () {
counter = counter + 1;
document.title = "Iteration: " + counter;
}, 8000 );
</script>
</body>
</html>
For use within your Script.js file in combination with jQuery, you might want to wrap it all in $(document).ready( function() {...} );
Update
Here's an example for displaying a different name every 8 seconds.
<!DOCTYPE html>
<html>
<head>
<title>Hello there!</title>
</head>
<body>
<script>
var names = [ "Rick", "Michonne", "Darryl", "Rosita", "Negan" ];
var counter = 0;
setInterval( function () {
document.title = "Hello " + names[ counter ];
if ( counter == names.length - 1 ) {
counter = 0;
} else {
counter = counter + 1;
}
}, 8000 );
</script>
</body>
</html>

My automatic image slider only shows the first two images

My automatic image slider only shows the first two images of the images array while tere are three images. I can't figure out why it is not working properly, I hope someone might know what is going wrong.
var images = [];
var i = 0;
//image array
images[0] = 'https://placeimg.com/900/600/animals?t=1515065784396';
images[1] = 'https://placeimg.com/900/600/animals?t=1515065867693';
images[2] = 'https://placeimg.com/900/600/animals?t=1515065784396';
function changeImage() {
"use strict";
document.getElementById("slider").src = images[i];
if (i < images.length - 1) {
i += 1;
} else {
i = 0;
}
setInterval(changeImage, 2000);
}
window.onload = changeImage;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Automatic Image Slider </title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<img id="slider">
</body>
</html>
Here it is! I've modified your code so that it now will work, pay attention not to reinitialize the interval at every changeImage() call ;)
//image array
var images = [];
images[0] = 'https://placeimg.com/900/600/animals?t=1515065784396';
images[1] = 'https://placeimg.com/900/600/animals?t=1515065867693';
images[2] = 'https://placeimg.com/900/600/animals?t=1515065784397';
var i = -1;
function changeImage() {
"use strict";
++i;
if (i >= images.length) {
i = 0;
}
document.getElementById("slider").src = images[i];
}
setInterval(changeImage, 2000);
window.onload = changeImage;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Automatic Image Slider </title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<img id="slider">
</body>
</html>
images.length = 3
but
images.length - 1 = 2
so
(i < images.length - 1)
this condition work inly for i = 0 and i = 1
use this condition instead
(i < images.length)
Actually, your code works with a little bug. Note that your first and last image is the same.
And the huge bug of your code is that you are creating a new interval at each changeImage call, so the last image is being placed but fastly replaced for the first image.
Remove the setInterval(changeImage, 2000) from the changeImage function and call it like this:
window.onload = function() {
changeImage();
setInterval(changeImage, 2000)
}
Because your condition if (i < images.length - 1) is true only for 0 an 1
If you do if (i<=images.length-1) you will get all the three images

Categories

Resources