Javascript Countdown Timer with New Window - javascript

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>

Related

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 to loop a display using setTimeout, setInterval or?

codepens below showing use of setTimeout, setInterval & location.reload
what other options are available?
next level I want is - add a control to allow the user to cycle forwards/backwards easily.
codepen using setTimeout & location.reload (requires reloading page - want to avoid this)
https://codepen.io/GuruAtWork/pen/PoPYbKK
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
<div id="info">start</div>
<script>
var elem = document.getElementById("info");
setTimeout(function () {
elem.innerHTML = "one";
}, 1000);
setTimeout(function () {
elem.innerHTML = "two";
}, 2000);
setTimeout(function () {
elem.innerHTML = "three";
}, 3000);
setTimeout(function(){
//window.location.reload(1);
location.reload()
}, 4000);
</script>
</body>
</html>
codepen using setInterval nested inside setTimeout
https://codepen.io/GuruAtWork/pen/rNOBjBa
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
<div id="info">start</div>
<script>
var elem = document.getElementById("info");
setTimeout(function () {
console.log("setTimeout 1000")
elem.innerHTML = "setTimeout 1000";
setInterval(function () {
elem.innerHTML = "setInterval one";
console.log("setInterval 1000")
}, 4000);
}, 1000);
setTimeout(function () {
console.log("setTimeout 2000")
elem.innerHTML = "setTimeout 2000";
setInterval(function () {
console.log("setInterval 2000")
elem.innerHTML = "setInterval two";
}, 4000);
}, 2000);
setTimeout(function () {
console.log("setTimeout 3000")
elem.innerHTML = "setTimeout 3000";
setInterval(function () {
console.log("setInterval 3000")
elem.innerHTML = "setInterval three";
}, 4000);
}, 3000);
</script>
</body>
</html>
You can use an array to store the contents, and loop the index. To go back/forward just change the value of i and update.
var contents=["one", "two", "three"], i = 0;
setInterval(function() {
document.getElementById("content").innerHTML = contents[i];
if (++i >= 3) i = 0;
}, 1000);
<div id='content'></div>

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>

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 setTimeout function with JQuery

I'm new to JQuery and Javascript, I try to write a small setTimeout function but it seems not to work. Below is my code, can some one help out by pointing out what is wrong here.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>countdown</title>
<script type="text/javascript" src="/jquery-2.1.4.js"></script>
<script>
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setTimeout(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
second--;
}, 1000);
});
</script>
</head>
<body>
<input type="text" id="input" value="25:23"/><br>
<button type="button" id="submit" value="send"></button>
</body>
</html>
Your code executes on .click on the submit button - which means it only executes when you click the button. Also using setTimeout you are only running it once, and by the inner logic of the function it seems you want it to be ongoing. Substitute setTimeout to setInterval to keep it running.
`$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setInterval(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
$('#input').val(minute + ':' + second);
}, 1000);
});`
have to recursive to make call and call again....
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>countdown</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<input type="text" id="input" value="25:23"/><br>
<input type="button" id="submit" value="send"></input>
<script>
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
//console.log( second);
setTimeout(function () {
rece();
function rece(){
if (minute == 0 && second == 0) {
alert("no time left");
console.log('no time left')
}
else if (second !== 0) {
second--;
console.log('second');
rece();
}
else {
minute--;
second = 60;
console.log('minute');
rece();
}
second--;
}
}, 100);
});
</script>
</body>
</html>
I've modified your code slightly and created a fiddle: JsFiddle
$("#submit").click(function(){
var timeVal = $("#input").val();
var mainTimeVal = timeVal.split(":");
var minute = parseInt(mainTimeVal[0]);
var second = parseInt(mainTimeVal[1]);
setTimeout(function () {
if (minute == 0 && second == 0) {
alert("no time left");
}
else if (second !== 0) {
second--;
}
else {
minute--;
second = 60;
}
second--;
$('#input').val(minute + ':' + second);
}, 1000);
});

Categories

Resources