How to go faster than a short setTimeout in javascript? - 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();
}

Related

How to create an insufficient balance message when the balance is 0?

<div id="balance">0.00</div>
<div id="sum">0.01</div>
<div id="result">000</div>
<div id="message">000</div>
<button>ROLL</button>
var x = 0;
$(document).ready(function(){
$("button").click(function () {
var num = setInterval(function () {
$("#result").text(Math.floor(Math.random() * 100))
}, 10);
setTimeout(function () {
clearInterval(num);
var sum = parseFloat($("#sum").html());
var fnal = $("#result").html();
if (fnal > 50) {
x += sum;
$("#balance").text(x.toFixed(2));
$("#message").text("Balance insufficient!");
}
else {
x -= sum;
$("#balance").text(x.toFixed(2));
$("#message").text("Balance insufficient!");
}
},500);
});
});
I don't know how to do this within (if) and (else) instruction.
So, please how can I do this? and I'll appreciate your efforts.
Please try to this code i hope helpfull thanks.
var x = 0;
$(document).ready(function(){
$("button").click(function () {
var num = setInterval(function () {
$("#result").text(Math.floor(Math.random() * 100))
}, 10);
setTimeout(function () {
clearInterval(num);
var sum = parseFloat($("#sum").html());
var fnal = $("#result").html();
if (true) {
x += sum;
$("#balance").text(x.toFixed(2));
$("#message").text(x === 0 ? "Balance insufficient!" : '');
}
else {
x -= sum;
$("#balance").text(x.toFixed(2));
$("#message").text(x === 0 ? "Balance insufficient!" : '');
}
},500);
});
});
I moved the balance and message out of the if/else to show a message when x === 0. Is this what youre looking for?
var x = 0;
$(document).ready(function() {
$("button").click(function() {
var num = setInterval(function() {
$("#result").text(Math.floor(Math.random() * 100));
}, 10);
setTimeout(function() {
clearInterval(num);
var sum = parseFloat($("#sum").html());
var fnal = parseFloat($("#result").html());
if (fnal > 50) {
x += sum;
} else {
x -= sum;
}
// Moved out of if/else, because it was the same
$("#balance").text(x.toFixed(2));
// If x === 0, show message, otherwise clear the text
$("#message").text(x === 0 ? "Balance insufficient!" : '');
}, 500);
});
});
Note: if you havent seen the <condition? ? <true> : <false> yet, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

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;
}
}
}

Javascript: Global Variables Aren't Defined In Other Functions

I have three variables that I need to put in the innerHTML of four spans. The variables I use are seconds, accurateclick, and inaccurateclick. The process I use to get these variables is fine. The problem is I can't figure out how to bring them over to another function. I will make a replica of what I have. This will be a simpler version.
var x;
var y;
var z;
function A(){
x = 1;
y = 2;
z = 3;
B();
}
function B(){
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
}
What would happen is, instead of a being equal to 1, b being equal to 2, and c being equal to 3, they would all equal to undefined. I don't know why that is happening when x, y, and z are global variables. I thought they should change when set to a different value.
Here is my actual code:
var seconds;
var accurateclicks;
var inaccurateclicks;
var windowheight = window.innerHeight;
var windowwidth = window.innerWidth;
var colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"];
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
function BeginGameLoad(){
var BottomLabel1 = document.getElementById("bl1");
var BeginGameContainer = document.getElementById("BGC1");
var RightClick = false;
BottomLabel1.addEventListener("mousedown", BL1MD);
BottomLabel1.addEventListener("mouseup", BL1MU);
BottomLabel1.style.cursor = "pointer";
window.addEventListener("resize", BeginGameResize);
window.addEventListener("contextmenu", BeginGameContextMenu);
function BeginGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL1MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel1.style.color = randomcolor;
RightClick = false;
}
}
function BL1MU(){
if(RightClick == false){
window.location.href = "Game.html";
GameLoad();
}
else{
RightClick = false;
}
}
if(windowheight < 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
BeginGameContainer.style.width = "800px";
}
function BeginGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
BeginGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
BeginGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
BeginGameContainer.style.width = "100%";
}
}
}
function GameLoad(){
var LeftPanel2 = document.getElementById("lp2");
var LeftColorPanel2 = document.getElementById("lcp2");
var TopPanel2 = document.getElementById("tp2");
var TopLabel2 = document.getElementById("tl2");
var RightPanel2 = document.getElementById("rp2")
var RightLabel2 = document.getElementById("rl2");
var GameContainer = document.getElementById("GC2");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var clickedRightName = false;
var clickedRightColor = false;
var clickedRightNameColor = false;
var RightClick = false;
var ClickedLeftColorPanel = false;
var ClickedRightLabel = false;
var ClickedTopLabel = false;
var Timer;
TopPanel2.addEventListener("mouseup", TP2MU);
TopLabel2.addEventListener("mousedown", TL2MD);
TopLabel2.addEventListener("mouseup", TL2MU);
TopLabel2.style.cursor = "pointer";
LeftPanel2.addEventListener("mouseup", LP2MU);
LeftColorPanel2.addEventListener("mouseup", LCP2MU);
LeftColorPanel2.addEventListener("mousedown", LCP2MD);
LeftColorPanel2.style.cursor = "pointer";
RightPanel2.addEventListener("mouseup", RP2MU);
RightLabel2.addEventListener("mouseup", RL2MU);
RightLabel2.addEventListener("mousedown", RL2MD);
RightLabel2.style.cursor = "pointer";
window.addEventListener("resize", GameResize);
window.addEventListener("contextmenu", GameContextMenu);
function AddSeconds(){
seconds++;
}
function GameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function TL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true){
TopLabel2.style.color = randomcolor;
RightClick = false;
}
}
function TP2MU(){
if(ClickedTopLabel == false){
inaccurateclicks++;
}
else{
ClickedTopLabel = false;
}
}
function TL2MU(){
ClickedTopLabel = true;
if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
accurateclicks++;
window.location.href = "EndGame.html";
EndGameLoad();
}
else if (!clickedRightName == true && !clickedRightColor == true && !clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
Timer = setInterval(AddSeconds, 1000);
seconds = 0;
accurateclicks = 0;
inaccurateclicks = 0;
TopLabel2.innerHTML = randomcolor;
RightClick = false;
}
else{
inaccurateclicks++;
}
RightClick == false
}
function LCP2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function LCP2MU(){
ClickedLeftColorPanel = true;
if(clickedRightColor == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == LeftColorPanel2.style.backgroundColor){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.color){
LeftColorPanel2.style.backgroundColorr = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.backgroundColor){
LeftColorPanel2.style.backgroundColor = randomcolor2;
accurateclicks++;
}
if (LeftColorPanel2.style.backgroundColor == randomcolor.toLowerCase()){
clickedRightColor = true;
LeftColorPanel2.style.cursor = "auto";
}
randomcolor2 = null;
RightClick = false;
}
else if(clickedRightColor == true && RightClick == false){
inaccurateclicks++;
}
}
function LP2MU(){
if(ClickedLeftColorPanel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
function RL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function RL2MU(){
ClickedRightLabel = true;
if(clickedRightName == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2 == RightLabel2.innerHTML){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2 != RightLabel2.innerHTML){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2 != RightLabel2.color){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
}
if (RightLabel2.innerHTML == randomcolor){
clickedRightName = true;
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == false && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == RightLabel2.style.color){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
}
if (RightLabel2.style.color == randomcolor.toLowerCase()){
clickedRightNameColor = true;
RightLabel2.style.cursor = "auto";
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == true && RightClick == false){
inaccurateclicks++;
}
}
function RP2MU(){
if(ClickedRightLabel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
if(windowheight < 600)
{
GameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
GameContainer.style.width = "800px";
}
function GameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
GameContainer.style.height = "600px";
}
if(windowheight > 600)
{
GameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
GameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
GameContainer.style.width = "100%";
}
}
}
function EndGameLoad(){
var BottomLabel3 = document.getElementById("bl3");
var EndGameContainer = document.getElementById("EGC3");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var RightClick = false;
BottomLabel3.addEventListener("mousedown", BL3MD);
BottomLabel3.addEventListener("mouseup", BL3MU);
BottomLabel3.style.cursor = "pointer";
window.addEventListener("resize", EndGameResize);
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
window.addEventListener("contextmenu", EndGameContextMenu);
function EndGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL3MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true
}
else{
randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel3.style.color = randomcolor;
RightClick = false;
}
}
function BL3MU(){
if(RightClick == false){
MiddleLabelTwo.innerHTML = "Time (Seconds): "
MiddleLabelThree.innerHTML = "Accurate Clicks: "
MiddleLabelFour.innerHTML = "Inaccurate Clicks: "
MiddleLabelFive.innerHTML = "Score: "
window.location.href = "Game.html";
}
}
if(windowheight < 600)
{
EndGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
EndGameContainer.style.width = "800px";
}
function EndGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
EndGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
EndGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
EndGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
EndGameContainer.style.width = "100%";
}
}
}
Whenever I run it, it works up to this point
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
It says seconds, accurateclicks, and inaccurateclicks are all undefined. I don't know why this would happen given that they were defined in the previous function [Game()].
try writing,
x = 1;
y = 2;
z = 3;
function A() {
B();
}
function B() {
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
console.log(a, b, c, d);
}
A();
Reason: 'var' defines variables locally!
You did make two html files and this caused the js file to reload. This is why the global variables are declared again and are renewed to undefined.The solution is to work with one html file and to only reload the body.
My syntax was right, but as #Julie mentioned, the variables were being reloaded. How to get JS variable to retain value after page refresh? this helped me solve my problem.

Loop doesn't change content within div

This loop is supposed to increment the variable x every 15 seconds and depending upon what value x is the appropriate content is shown, the problem is that x doesn't increment.
var x = 1;
function slider() {
if (x > 4) {
x = 1;
}
if (x == 1) {
document.writeln("<div id='picture_slider_info'><h3>Example one</h3></div>");
} else if(x == 2) {
document.writeln("<div id='picture_slider_info'><h3>Example two</h3></div>");
} else if (x == 3) {
document.writeln("<div id='picture_slider_info'><h3>Example three</h3></div>");
} else {
document.writeln("<div id='picture_slider_info'><h3>Example four</h3></div>");
}
x++
}
setInterval(slider(), 15000);
You are not incrementing the variable x.
Change your code to:
var x = 1;
function slider() {
x++; // x incremented.
if (x > 4) {
x = 1;
}
if (x == 1) {
document.writeln("<div id='picture_slider_info'><h3>Example one</h3></div>");
} else if(x == 2) {
document.writeln("<div id='picture_slider_info'><h3>Example two</h3></div>");
} else if (x == 3) {
document.writeln("<div id='picture_slider_info'><h3>Example three</h3></div>");
} else {
document.writeln("<div id='picture_slider_info'><h3>Example four</h3></div>");
}
}
setInterval(slider(), 15000);
You shouldn't be calling slider(), instead, pass the function as argument to setInterval:
setInterval(slider, 1500).
You are currently passing the return result of slider() which is undefined to setInterval.
Nikola Dimitroff is right.
I'm giving this as an answer to give you the code.
<html>
<head>
<script type="text/javascript">
var x = 1;
function slider() {
console.log(x);
if (x > 4) { x = 1; }
if (x == 1) { console.log("One"); }
else if(x == 2) { console.log("Two"); }
else if (x == 3) { console.log("Three"); }
else { console.log("More"); }
x++
}
setInterval(slider, 1000);
</script>
</head>
<body>
</body>
</html>

Float-In Div needs delay

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

Categories

Resources