How to make stop button in Javascript to stop everything - javascript

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>

Related

how to change image for every 4 seconds in 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>

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>

Problem with the countdown timer JS - IF Condition

I'm new to JavaScript and this website.
I have the following code for an event timer countdown:
https://codepen.io/iraffleslowd/pen/povGNdo
My problem really is with an if condition.
setInterval(function () {
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
Because my event does not expire at the end of the countdown, it ends approximately one hour after starting.
So can someone help me add another condition so that in the interval of that time instead of showing me Expired, it shows Live or something similar?
Thank you so much!
You want to manage 3 different states...
Counting down until LIVE
LIVE
EXPIRED
(() => {
const intervalId = setInterval(() => {
// update countdown timer
if (distance < -(ELAPSED_GAMETIME_IN_MS)) {
// set EXPIRED
clearInterval(intervalId);
}
else if (distance < 0) {
// set LIVE
}
}, 1000);
})();
EDIT
Working example
This example utilizes moment because it's a great utility that provides all necessary math and formatting for dates and is perfect for this scenario.
<!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>Document</title>
</head>
<body>
<div id="countdown"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<script>
(() => {
const countdownEl = document.getElementById("countdown");
const START_DATE = moment("2020-01-22");
const ELAPSED_GAMETIME_IN_MS = 1000 * 60 * 60 * 2; // 2 hours in milliseconds
const intervalId = setInterval(() => {
const TIME_FROM_START = START_DATE.diff(moment());
countdownEl.innerHTML = START_DATE.fromNow(); // This could be modified to show different levels of granularity...
if (TIME_FROM_START < -ELAPSED_GAMETIME_IN_MS) {
countdownEl.innerHTML = "EXPIRED";
clearInterval(intervalId);
} else if (TIME_FROM_START < 0) {
countdownEl.innerHTML = "LIVE";
}
}, 1000);
})();
</script>
</body>
</html>
It looks like an else-statement can resolve your issue.
Try
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
else {
document.getElementById("demo").innerHTML = "LIVE";
}

Stop jQuery timer at 0 using clearInterval

I'm having issues using clearInterval to stop my simple count timer once it is equal to 0. Essentially, timer goes past 0 into negative values instead of stopping at 0. I am creating a basic quiz that ideally will alert the user of the correct answers once the timer reaches and stops at 0.
Below is current code:
var count = 10;
var gameTime;
gameTime = setInterval("counter()", 1000);
function convertSeconds(s){
var min = Math.floor(s / 60);
var sec = s % 60;
return min + ":" + sec;
}
function counter(){
count--;
$("#timer").text(convertSeconds(count));
}
if (count === 0) {
clearInterval("#timer");
} else {
//Do nothing
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trivia</title>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div id ="timer">10</div>
</body>
Just move your if check into the counter function and clear the gameTime variable.
setInterval runs the provided function at the given interval so anything you want to run or check on that interval must happen in the provided function.
var count = 10;
var gameTime;
gameTime = setInterval("counter()", 1000);
function convertSeconds(s){
var min = Math.floor(s / 60);
var sec = s % 60;
return min + ":" + sec;
}
function counter(){
count--;
$("#timer").text(convertSeconds(count));
if (count === 0) {
clearInterval(gameTime);
} else {
//Do nothing
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Trivia</title>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div id ="timer">10</div>
</body>

Javascript Countdown Timer with New Window

I don't really know javascript, but I hacked together (i.e. found) the following code that does exactly what I want, EXCEPT, I want the window focus to end up on the one with the countdown timer. In other words, I want to open the yahoo.com window, but not put it in focus.
Edit: I only really need this to work in IE11.
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language='JavaScript'>
var time = 10;
var page = "http://google.com";
function countDown(){
time--;
gett("container").innerHTML = time;
if(time == -1){
window.location = page;
}
}
function gett(id){
if(document.getElementById) return document.getElementById(id);
if(document.all) return document.all.id;
if(document.layers) return document.layers.id;
if(window.opera) return window.opera.id;
}
function init(){
if(gett('container')){
setInterval(countDown, 1000);
gett("container").innerHTML = time;
}
else{
setTimeout(init, 50);
}
}
document.onload = init();
window.open('http://www.yahoo.com');
</SCRIPT>
</head>
<body>
<H2>Google loading in <span id="container"></span> seconds...</H2>
</body>
</html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language='JavaScript'>
var time = 10;
var page = "http://google.com";
function countDown(){
time--;
gett("container").innerHTML = time;
if(time == -1){
window.open('http://www.yahoo.com',"_blank","toolbar=yes, scrollbars=yes, resizable=yes, top=500, left=500, width=400, height=400");
}
}
function gett(id){
if(document.getElementById) return document.getElementById(id);
if(document.all) return document.all.id;
if(document.layers) return document.layers.id;
if(window.opera) return window.opera.id;
}
function init(){
if(gett('container')){
setInterval(countDown, 1000);
gett("container").innerHTML = time;
}
else{
setTimeout(init, 50);
}
}
document.onload = init();
</SCRIPT>
</head>
<body>
<H2>Google loading in <span id="container"></span> seconds...</H2>
</body>
</html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h2>Google loading in <span id="counter">3</span> seconds...</h2>
<script>
document.onload = init()
$elem = document.getElementById("counter");
var timer = $elem.innerHTML;
//timer = 30; //if you want start timer from javascript or change time inside counter
function init() {
var interval = setInterval(function() {
timer = timer-1;
$elem.innerHTML = timer;
if(timer == 0) {
var popWindow = window.open("http://google.com", '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');
popWindow.blur();
window.focus();
window.onblur = window.focus();
clearInterval(interval);
}
},1000);
}
</script>
</body>
</html>

Categories

Resources