how to loop a display using setTimeout, setInterval or? - javascript

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>

Related

setInterval implementation problems

I am trying to implement a function that changes the value of a variable (paddle speed in a simple pong game) but the timer is running very fast and the paddle speed doesn't seem to be changing correctly.
I've created a function that executes each time the start game button is pressed, which I'm using as a timer:
function setTimer () {
setInterval(function () {
trialWindow += 1;
}, 1000);
console.log(trialWindow);
}
This timer is executed by pressing the start button
startBtn.addEventListener('click', setTimer);
I have another function set up to increment canvas.paddleOneVelocityY whenever the trialWindow variable is a multiple of 15
function userSpeed () {
if (trialWindow % 15 === 0)
{canvas.paddleOneVelocityY = getRandomNumber(5, 20)};
console.log(canvas.paddleOneVelocityY);
}
these functions are called in the startGame function:
function startGame() {
gameInProgress = true;
gameplay.className = '';
startMenu.className = '';
gameOverMenu.className = '';
pauseMenu.className = '';
gamePaused = false;
gameInterval = window.setInterval(function() {
moveEverything();
drawEverything();
setTimer();
userSpeed();
}, 1000/fps);
}
I've tried moving setTimer and userSpeed to different positions in the order of functions called in gameInterval and the timer seems to stop completely.
any help would be very much appreciated!
setTimer creates a new interval timer (a timer that repeats) every time it's called. You're calling it from inside the callback of another interval timer:
gameInterval = window.setInterval(function() { // <== This function repeats
moveEverything();
drawEverything();
setTimer(); // <== This creates a repeating
userSpeed(); // timer every time it's called
}, 1000/fps);
Instead, just call setTimer once, when you want to start the timer it starts.
Regarding your outer timer running at 1000/fps milliseconds, you might want to look at requestAnimationFrame.
Here is what you want:
function setTimer() {
setInterval(function () {
trialWindow += 1;
userSpeed();
console.log(trialWindow);
}, 1000);
}
function userSpeed() {
if (trialWindow % 15 === 0) {
canvas.paddleOneVelocityY = getRandomNumber(5, 20)
};
console.log(canvas.paddleOneVelocityY);
}
function startGame() {
gameInProgress = true;
gameplay.className = '';
startMenu.className = '';
gameOverMenu.className = '';
pauseMenu.className = '';
gamePaused = false;
setTimer();
gameInterval = window.setInterval(function () {
moveEverything();
drawEverything();
}, 1000 / fps);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="startGame()">Start</button>
</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>

jQuery - mousedown - do thing after time and repeat until mouseup

I have this code. It is animating car icon on google maps api.
$("#p_inc").mousedown(function () {
if(mouseDownAnim) clearInterval(mouseDownAnim);
moveCar();
mouseDownInc = true;
this.timer = setTimeout(function(){
if(mouseDownInc){
mouseDownAnim = setInterval(function () {
moveCar();
}, 150);
}
else{
if(mouseDownAnim) clearInterval(mouseDownAnim);
}
},200);
})
$("#p_dec").mousedown(function () {
backCar();
if(mouseDownAnim) clearInterval(mouseDownAnim);
mouseDownDec = true;
this.timer = setTimeout(function(){
if(mouseDownDec){
mouseDownAnim = setInterval(function () {
backCar();
}, 150);
}
else{
if(mouseDownAnim) clearInterval(mouseDownAnim);
}
},200);
});
$(document).on('mouseup',function(){
mouseDownInc = false;
mouseDownDec = false;
clearInterval(mouseDownAnim);
});
What i expect? When i click on button then moveCar() should trigger once, but when i click and hold button - moveCar() should trigger once , wait a 200ms and after that should repeat moveCar() every 150ms until i do mouseup. It is working but sometimes setInterval stack and i cant stop it. Where is bug?
JSFIDDLE: https://jsfiddle.net/2hbkrs6m/
working code
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>- jsFiddle demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<link href="/css/result-light.css" type="text/css" rel="stylesheet">
<style type="text/css"></style>
<script type="text/javascript">
$(function(){
var mouseDownInc = false;
var mouseDownDec = false;
var mouseDownAnim = null;
$("#p_inc").mousedown(function (event) {
if(mouseDownAnim) clearInterval(mouseDownAnim);
moveCar();
mouseDownInc = true;
if(mouseDownInc){
mouseDownAnim = setInterval(function () {
moveCar();
}, 150);
}
});
$("#p_dec").mousedown(function (event) {
if(mouseDownAnim) clearInterval(mouseDownAnim);
backCar();
mouseDownDec = true;
if(mouseDownDec){
mouseDownAnim = setInterval(function () {
backCar();
}, 150);
}
});
$(document).on('mouseup',function(){
mouseDownInc = false;
mouseDownDec = false;
clearInterval(mouseDownAnim);
});
function moveCar(){console.log("movecar")
}
function backCar(){console.log("backcar")
}
});
</script>
</head>
<body>
<button id="p_inc">Move</button>
<button id="p_dec">Back</button>
</body>
</html>

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>

JavaScript undefined variable in an anonymous function

This code is supposed to switch the display property of all children elements of #slide-container to "block" with time delay two seconds between the switches.
var magic = window.setInterval(function(){
if (document.readyState === "complete") {
var children = document.getElementById('slide-container').children;
for (var i = 0; children.length > i; i++ ) {
setTimeout(function(){
children[i].style.display = "block";
console.log(i);
},2000);
}
magic = window.clearInterval(magic);
} else {
console.log("...");
}
}, 1000);
I am using it along with this html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
</head>
<body>
<ul id="slide-container">
<li style="display: none;"><img src="http://i.imgur.com/8qBcyzc.jpg"></li>
<li style="display: none;"><img src="http://i.imgur.com/oxMTFTF.png"></li>
<li style="display: none;"><img src="http://i.imgur.com/JTM6Yqg.jpg"></li>
</ul>
</body>
</html>
I get error Uncaught TypeError: Cannot read property 'style' of undefined
It says it cannot find children or children[0]. But that variable has been specified and the dom nodes exist.
Closure issue.
Try adding a 3rd parameter to the setTimeout (doesn't work):
setTimeout(function(i){
children[i].style.display = "block";
console.log(i);
}, 2000, i);
Example
Another formate:
var i = 0;
var timer = setInterval(function () {
children[i].style.display = "block";
i++;
if (i == children.length) {
clearInterval(timer);
}
}, 2000);
EXAMPLE
ES6 is around the corner, the let statement is especially built for situations like this:
for (let i = 0; children.length > i; i++ ) {
setTimeout(function(){
children[i].style.display = "block";
console.log(i);
}, 2000);
}
However this is not the answer you need for right now. This was just a note.
Try encasing the setTimeout in an IIFE (Immediately invoked function expression)
for (var i = 0; children.length > i; i++) {
(function (index) {
setTimeout(function () {
children[index].style.display = "block";
console.log(i);
}, 2000);
})(i);
}
Check Fiddle
The reference of i is common to all the functions executed by setTimeout . So by the time the function inside executes , the value of i will point to children.length .
But there is no element that refers to children[children.length] which does not exist and throws an error.
By the time setTimeout is ready i will be the length of children so you have to capture the value of i
try this
var time = 2000;
for (var i = 0; children.length > i; i++ ) {
(function( child, time) {
window.setTimeout(function() {
child.style.display = "block";
}, time);
}( children[i], time));
time += 2000;
}
or you could do this. ... I have fixed the delay thing
var hideElement = function( element, time) {
window.setTimeout(function() {
element.style.display = 'block';
}, time);
};
var time = 2000;
for (var i = 0; children.length > i; i++ ) {
hideElement(children[i], time);
time += 2000;
}

Categories

Resources