Float-In Div needs delay - javascript

The following code below launches a float-in div when my webpage loads, however I need it to have a 60 second delay before it launches. Can anyone help? You can see a demo of the float-in div on www.bizassist.co.za.
Thank you.
Code:
var timer;
var h = -450;
var w = 500;
var t = 150;
function startAp() {
setLeft();
showAp();
}
function hideAp() {
if (document.layers) {
document.layers.pa.visibility = 'hide';
} else if (document.all) {
document.all.pa.style.visibility = 'hidden';
} else if (document.getElementById) {
document.getElementById("pa").style.visibility = 'hidden';
}
}
function showAp() {
state=typeof tPos;
if(state=='undefined') {
tPos = h;
}
if(tPos < t) {
tPos+=25;
if (document.layers) {
document.layers.pa.top = tPos+"px";
} else if (document.all) {
document.all.pa.style.top = tPos+"px";
} else if (document.getElementById) {
document.getElementById("pa").style.top = tPos+"px";
}
}
if(timer!=null) clearInterval(timer);
timer = setTimeout("showAp()",30);
}
function getoPos() {
if (document.layers) {
alert(document.layers.pa.top);
} else if (document.all) {
alert(document.all.pa.style.top);
} else if (document.getElementById) {
alert(document.getElementById("pa").style.top);
}
}
function setLeft() {
if (document.layers) {
document.layers.pa.left = ((window.innerWidth / 2) - (w / 2))+"px";
} else if (document.all) {
document.all.pa.style.left = ((document.body.offsetWidth / 2) - (w / 2))+"px";
} else if (document.getElementById) {
document.getElementById("pa").style.left = ((window.innerWidth / 2) - (w / 2)) + "px";
}
}

Use the setTimeout funcion to execute a function after some delay. Eg
setTimout(showApp, 6000) // time is in milliseconds

Related

how to make javascript game touch friendly?

I created flappy bird by following a youtube tutorial. Inside Bird.js there is a function called handleJump, inside that function when i put "Space", the bird jumps whenever i press space key on keyboard, but when i change it to "touchstart" the bird doesn't jump when i touch the screen! what am i doing wrong? what should i do?
The main page ( f.js ):
import { updateBird, setupBird, getBirdRect } from "./Bird.js";
import {
updatePipes,
setupPipes,
getPassedPipesCount,
getPipesRects,
} from "./Pipe.js";
//document.addEventListener("keypress", handleStart, { once: true });
document.addEventListener("touchstart", handleStart, { once: true });
const title = document.querySelector("[data-title]");
const subtitle = document.querySelector("[data-subtitle]");
let lastTime;
function updateLoop(time) {
if (lastTime == null) {
lastTime = time;
window.requestAnimationFrame(updateLoop);
return;
}
const delta = time - lastTime;
updateBird(delta);
updatePipes(delta);
if (checkLose()) return handleLose();
lastTime = time;
window.requestAnimationFrame(updateLoop);
}
function checkLose() {
const birdRect = getBirdRect();
const insidePipe = getPipesRects().some((rect) =>
isCollision(birdRect, rect)
);
const outsideWorld = birdRect.top < 0 || birdRect.bottom > window.innerHeight;
return outsideWorld || insidePipe;
}
function isCollision(rect1, rect2) {
return (
rect1.left < rect2.right &&
rect1.top < rect2.bottom &&
rect1.right > rect2.left &&
rect1.bottom > rect2.top
);
}
function handleStart() {
title.classList.add("hide");
setupBird();
setupPipes();
lastTime = null;
window.requestAnimationFrame(updateLoop);
}
function handleLose() {
setTimeout(() => {
title.classList.remove("hide");
subtitle.classList.remove("hide");
subtitle.textContent = `${getPassedPipesCount()} Pipes`;
document.addEventListener("touchstart", handleStart, { once: true });
}, 100);
}
Bird.js :
const birdElem = document.querySelector("[data-bird");
const BIRD_SPEED = 0.5;
const JUMP_DURATION = 120;
let timeSinceLastJump = Number.POSITIVE_INFINITY;
export function setupBird() {
setTop(window.innerHeight / 2);
document.removeEventListener("touchstart", handleJump); //keydown
document.addEventListener("touchstart", handleJump); //keydown
}
export function updateBird(delta) {
if (timeSinceLastJump < JUMP_DURATION) {
setTop(getTop() - BIRD_SPEED * delta);
} else {
setTop(getTop() + BIRD_SPEED * delta);
}
timeSinceLastJump += delta;
}
export function getBirdRect() {
return birdElem.getBoundingClientRect();
}
function setTop(top) {
birdElem.style.setProperty("--bird-top", top);
}
function getTop() {
return parseFloat(getComputedStyle(birdElem).getPropertyValue("--bird-top"));
}
function handleJump(e) {
if (e.code !== "touchstart") return;
timeSinceLastJump = 0;
}
I fixed it by removing the return
Before:
function handleJump(e) {
if (e.code !== "touchstart") return;
timeSinceLastJump = 0;
}
After:
function handleJump(e) {
if (e.code !== "touchstart");
timeSinceLastJump = 0;
}

Stop recursive setTimeout function

Im running a recursive setTimeout function and I can run it many times, it has a clearTimeout, with this property I can handle how to stop the function running.
But I can't figure out how to stop it in another function.
var a = 0;
var b = 0;
function Listener(x, y) {
var lValue = y == true ? a : b;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
setTimeout(Listener.bind(this, x, y), 1000);
} else {
clearTimeout(Listener);
if(y == true){
a=0;
}else{
b=0;
}
}
}
When i tried to run it twice, it works:
My doubt is: How can I stop a particular running instance.
A couple notes:
Given the constant timeout of 1000, you should be using setInterval() instead. It will greatly simplify your function, and allow you to cancel the interval whenever you want.
Using global variables is code smell, create an object instead to hold a reference to the value being incremented. Doing so will also allow your function parameters to be more intuitive.
Here's a solution incorporating these two suggestions:
function range (step, start = 0, stop = 100) {
const state = {
value: start,
interval: setInterval(callback, 1000)
};
function callback () {
if (state.value < stop) {
console.log(state.value);
state.value += step;
} else {
console.log('timer done');
clearInterval(state.interval);
}
}
callback();
return state;
}
const timer1 = range(10);
const timer2 = range(20);
setTimeout(() => {
console.log('stopping timer 1');
clearInterval(timer1.interval);
}, 2500);
setTimeout(() => {
console.log('timer 2 value:', timer2.value);
}, 3500);
You could elevate the timer to a higher scope that is accessible by other functions.
var a = 0;
var b = 0;
var timer = null;
function Listener(x, y) {
var lValue = y == true ? a : b;
if (lValue < 100) {
console.log(lValue);
if (y == true) {
a += x;
} else {
b += x;
}
timer = setTimeout(Listener.bind(this, x, y), 1000);
} else {
clearTimeout(timer);
if (y == true) {
a = 0;
} else {
b = 0;
}
}
}
function clearTimer() {
if (timer !== null) clearTimeout(timer);
}
Listener(3, 3);
// clear the timer after 3 secnods
setTimeout(clearTimer, 3000);
create a variable and store the reference of setTimout on that variable, after that you just clearTimout with that variable reference
e.x
GLOBAL VARIABLE:
var k = setTimeout(() => { alert(1)}, 10000)
clearTimeout(k)
var a = 0;
var b = 0;
var recursiveFunctionTimeout = null;
function Listener(x, y) {
var lValue = y == true ? a : b;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
recursiveFunctionTimeout = setTimeout(Listener.bind(this, x, y), 10);
} else {
clearTimeout(recursiveFunctionTimeout);
if(y == true){
a=0;
}else{
b=0;
}
}
}
LOCAL VARIABLE:
var a = 0;
var b = 0;
function Listener(x, y) {
var lValue = y == true ? a : b;
var recursiveFunctionTimeout = null;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
recursiveFunctionTimeout = setTimeout(Listener.bind(this, x, y), 10);
} else {
clearTimeout(recursiveFunctionTimeout);
if(y == true){
a=0;
}else{
b=0;
}
}
}

if statement of button found

My goal is, if a page contains the specified button, click it, and increase the amt_clicked by 1. When amt_clicked is greater than 15, wait for 60 seconds and reset amt_clicked. I have no idea how do this if statement. Example:
var amt_clicked = 0;
while (1) {
while (amt_clicked < 15) {
if (button found) { // this is where I am lost
iimPlay("TAG POS={{amt_clicked}} TYPE=BUTTON ATTR=TXT:Get");
amt_clicked++;
}
}
iimPlay("WAIT SECONDS=60");
amt_clicked = 0;
}
This will run 20 times per second, using the window.setInterval() function:
var amt_clicked = 0;
var amt_cooldown = 1200;
setInterval(function(){
if (amt_cooldown === 0)
amt_cooldown = 1200;
else if (amt_cooldown < 1200)
amt_cooldown -= 1;
else if (amt_clicked > 15) {
amt_clicked = 1;
amt_cooldown -= 1;
} else {
amt_clicked -= 1;
//Click
}, 50);
You can use combination of setInterval and setTimeout.
I have added comments to code for you to understand.
var amt_clicked = 0;
var setTimeoutInProcess = false;
//processing the interval click function
setInterval(() => {
checkButtonAgain();
}, 200);
function checkButtonAgain() {
var element = document.getElementById('iNeedtoBeClicked');
//if clicked 15 times then need to wait for 60 seconds
if (amt_clicked === 15) {
if (!setTimeoutInProcess) {
setTimeoutInProcess = true;
setTimeout(function() {
//resetting the amt-clicked
amt_clicked = 0;
setTimeoutInProcess = false;
}, 60000);
} else {
console.log('waiting');
}
} else if (typeof(element) != 'undefined' && element != null) {
//triggering click and increasing the amt_clicked
element.click();
amt_clicked++;
}
console.log(amt_clicked);
}
<button id="iNeedtoBeClicked">Click ME Button</button>

Javascript animation won't work in IE

I have a small javascript animation that shows a new dropdown select menu after the previous one has been chosen.
Heres the HTML:
<div class="steps">
<div id="step1">
<button type="button" class="button standardBtn" style="opacity: 1.5" id="toJapanese" onclick="setToJapanese(); activatePullDown()">To Japanese</button>
<button type="button" class="button standardBtn" style="opacity: 1.5" id="toWestern" onclick="setToWestern(); activatePullDown()">To Western</button>
</div>
<div id="step2" style="opacity: 0"></div>
<div id="step3" style="opacity: 0"></div>
<div id="step4" style="opacity: 0"></div>
</div>
When a button from step1 is clicked, the first menu, step2, appears. When an item from step2 is selected, it moves to the left and a new menu, step3, shows. It works in every browser except IE (10 and 11). In IE, step2 moves over correctly, but step3 fails to show.
Heres my Javascript for when step2 is selected.
function yearSelected() {
startMoveLeft('step3');
getMonths();
setTimeout(fadeIn, 600, 'step3', 'normal', 0);
}
function startMoveLeft(id) {
var element = document.getElementById(id);
var mq = window.matchMedia( "(min-width: 800px)" );
var display = [];
if (mq.matches) {
display = 'inline-block';
}
else {
display = 'block';
}
element.style.display = display;
element.style.visibility = 'visible';
element.style.width = '0px';
doMoveLeft(element);
}
function doMoveLeft(element) {
console.log(element.style.width);
if (parseInt(element.style.width, 10) < convertEmToPx(8)) {
var width = parseInt(element.style.width) + 4 + 'px';
element.style.width = width;
setTimeout(function() {
doMoveLeft(element);
}, 1);
}
}
function getMonths() {
var xmlhttp = createXmlhttp();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('toJapanese').className += ' activeButton';
document.getElementById('toWestern').className += ' unactiveButton';
document.getElementById('step3').innerHTML = xmlhttp.responseText;
}
};
var year = document.getElementById("yearSelect").value;
var token = document.getElementsByTagName('input').item(name = "_token").value;
var data = "_token=" + token + "&year=" + year;
xmlhttp.open("POST", "ajax/getMonths", true);
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
function fadeIn(id, time, fade) {
var element = document.getElementById(id);
if (element.style.opacity < 1) {
FX.fadeIn(element, {
duration: setDuration(time)
}, fade);
}
}
function setDuration(time) {
if (time === 'very_fast') {
return 200;
}
else if (time === 'fast') {
return 400;
}
else if (time === 'normal') {
return 600;
}
else if (time === 'slow') {
return 800;
}
else if (time === 'very_slow') {
return 1000;
}
else {
return 0;
}
}
(function() {
var FX = {
easing: {
linear: function(progress) {
return progress;
},
quadratic: function(progress) {
return Math.pow(progress, 2);
},
swing: function(progress) {
return 0.5 - Math.cos(progress * Math.PI) / 2;
},
circ: function(progress) {
return 1 - Math.sin(Math.acos(progress));
},
back: function(progress, x) {
return Math.pow(progress, 2) * ((x + 1) * progress - x);
},
bounce: function(progress) {
for (var a = 0, b = 1, result; 1; a += b, b /= 2) {
if (progress >= (7 - 4 * a) / 11) {
return -Math.pow((11 - 6 * a - 11 * progress) / 4, 2) + Math.pow(b, 2);
}
return 0;
}
},
elastic: function(progress, x) {
return Math.pow(2, 10 * (progress - 1)) * Math.cos(20 * Math.PI * x / 3 * progress);
}
},
animate: function(options) {
var start = new Date();
var id = setInterval(function() {
var timePassed = new Date() - start;
var progress = timePassed / options.duration;
if (progress > 1) {
progress = 1;
}
options.progress = progress;
var delta = options.delta(progress);
options.step(delta);
if (progress == 1) {
clearInterval(id);
options.complete;
}
}, options.delay || 10);
},
fadeOut: function(element, options, to) {
if (to === undefined) {
to = 1;
}
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return FX.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to - delta;
}
});
},
fadeIn: function(element, options, to) {
if (to === undefined) {
to = 0;
}
if (element.style.opacity === 0) {
to = 0;
}
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return FX.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to + delta;
}
});
}
};
window.FX = FX;
})();
Ive tested these functions all individually and they work fine, but together something is not right. Id really appreciate some insight.
UPDATE: It has something to do with the AJAX request. Its not picking up the _token value. This line seems to be causing the problem:
document.getElementsByTagName('input').item(name = "_token").value;
The item function of HTMLCollection takes an integer argument (an index), not a CSS selector (you can't pass a selector like that, anyway). You probably meant to say this:
var token = document.querySelector("input[name='_token']").value;

How to go faster than a short setTimeout in javascript?

How to make a script repeat it self faster than a setTimeout allows but still not as fast as possible?
Check this demo for 2 examples.
(I post the demo code under also)
var x = 0;
var divEl = document.getElementById('counter');
var divEl2 = document.getElementById('counter2');
document.getElementById('gosettimeout').addEventListener('click', go, false);
document.getElementById('gotoofast').addEventListener('click', go2, false);
function go() {
x++;
divEl.innerHTML = x;
if (x > 100) {
return false;
}
setTimeout(function () {
go();
}, 0);
}
function go2() {
x++;
divEl2.innerHTML = x;
if (x > 100) {
return false;
}
go2();
}
var x = 0;
var divEl = document.getElementById('counter');
var divEl2 = document.getElementById('counter2');
document.getElementById('gosettimeout').addEventListener('click', go, false);
document.getElementById('gotoofast').addEventListener('click', go2, false);
function go() {
x++;
divEl.innerHTML = x;
if (x > 100) {
return false;
}
if (x % 2 == 0) {
setTimeout(function () {
go();
}, 0);
} else {
go();
}
}
function go2() {
x++;
divEl2.innerHTML = x;
if (x > 100) {
return false;
}
go2();
}
Two times faster, but not as fast as possible =)
var x = 0;
var divEl = document.getElementById('counter');
var divEl2 = document.getElementById('counter2');
document.getElementById('gosettimeout').addEventListener('click', go, false);
document.getElementById('gotoofast').addEventListener('click', go2, false);
function go() {
divEl.innerHTML = ++x;
if (x > 100) {
return false;
}
if (x % 5 == 0) {
setTimeout(function () {
go();
}, 0);
} else {
go();
}
}
function go2() {
x++;
divEl2.innerHTML = x;
if (x > 100) {
return false;
}
go2();
}

Categories

Resources