Save number counter count - jquery

I'm trying to create a counter which starts from a defined number and then counts to infinity. I'm using localstorage to save the count but I would like to have it read from a text file.
This is the code that I'm using right now. As you can see I'm saving the counter on localstorage but I would like to show the same number to every visitor of my website. For that, I guess I have to save and load these from a file?
<span id="liveNumbers"></span>
if(window.localStorage) {
var updateInterval = 1000; //ms
function randomRange() {
return Math.floor(Math.random()*3)+1;
}
$(document).one('ready', function () {
localStorage.clear();
});
var counter = +localStorage.getItem('counter');
if (!counter) { //first load
counter = 450000;
} else {
var lastSessionEnd = +localStorage.getItem('lastSessionEnd');
for(var l = Math.floor((getUnixTimeStamp() - lastSessionEnd)*1000/updateInterval); l--;) {
counter += randomRange();
}
}
var liveNumbers = document.getElementById('liveNumbers');
function refreshDisplay() {
liveNumbers.innerHTML = commaSeparateNumber(counter);
}
refreshDisplay();
setInterval(function() {
counter += randomRange();
refreshDisplay();
}, updateInterval);
function commaSeparateNumber(val) {
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return val;
}
function getUnixTimeStamp() {
return Math.floor(Date.now()/1000);
}
window.addEventListener('beforeunload', function() {
localStorage.setItem('counter', counter);
localStorage.setItem('lastSessionEnd', getUnixTimeStamp());
});
} else {
}

Related

JQuery: Putting a new funtion into my code stops all other functions

I'm having trouble with a temperature-based timer I'm building. I have a start function and functions to raise and lower the desired temperature, and then a countdown by seconds. The code:
$(document).ready(function(){
var desiredTemp = 10;
var actualTemp = 12;
var tempMatch = false;
var degreeTime = 5;
var seconds = degreeTime;
$("#actualBox").text(timer(seconds));
/*This returns the outcome of the tick and counter functions.*/
function timer(seconds) {
return actualTemp;
}
/*This checks whether the temp should drop by one or not.*/
function tick() {
if(seconds === 0) {
actualTemp -= 1;
seconds = degreeTime;
}
else {
seconds -= 1;
$("#actualBox").text(timer(seconds));
}
}
/*this sets the count interval to run the tick function every second*/
function counter() {
count = setInterval(tick, 1000);
}
/*functions to raise and lower desired temp*/
function changeTemp(degree) {
desiredTemp += degree;
}
function showDesired() {
return desiredTemp;
}
/*when you click Start, this runs the counter*/
$("#start").click(function(){
counter();
});
$('#lowerTemp').click(function(){
changeTemp(-1);
$('#desiredBox').text(showDesired());
});
$('#raiseTemp').click(function(){
changeTemp(1);
$('#desiredBox').text(showDesired());
});
});
Now when i insert this code anywhere:
function doneCheck() {
if actualTemp === desiredTemp;
jQuery('#actualBox').css({"background-color: green"});
}
The timer and change temp functions completely stop working. I have searched and not found any relevant information as to why. Can anyone please point me in the right direction?
Fix syntax errors
function doneCheck() {
if(actualTemp == desiredTemp)
$('#actualBox').css({"background-color: green;"});
}
There are some syntactical mistakes correct those and call doneCheck() function where do you want.
var desiredTemp = 10;
var actualTemp = 12;
var tempMatch = false;
var degreeTime = 5;
var seconds = degreeTime;
$(document).ready(function(){
$("#actualBox").text(timer(seconds));
/*This returns the outcome of the tick and counter functions.*/
function timer(seconds) {
return actualTemp;
}
/*This checks whether the temp should drop by one or not.*/
function tick() {
if(seconds === 0) {
actualTemp -= 1;
seconds = degreeTime;
}
else {
seconds -= 1;
$("#actualBox").text(timer(seconds));
}
}
/*this sets the count interval to run the tick function every second*/
function counter() {
count = setInterval(tick, 1000);
}
/*functions to raise and lower desired temp*/
function changeTemp(degree) {
desiredTemp += degree;
}
function showDesired() {
return desiredTemp;
}
/*when you click Start, this runs the counter*/
$("#start").click(function(){
counter();
});
$('#lowerTemp').click(function(){
changeTemp(-1);
$('#desiredBox').text(showDesired());
});
$('#raiseTemp').click(function(){
changeTemp(1);
$('#desiredBox').text(showDesired());
});
});
function doneCheck() {
if(actualTemp === desiredTemp)
jQuery('#actualBox').css("background-color","green");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">start</button>
<button id="lowerTemp">lowerTemp</button>
<button id="raiseTemp">raiseTemp</button>
<button id="desiredBox">desiredBox</button>
<button id="actualBox">actualBox</button>

jquery Increasing score after matching random numbers

I've been trying to figure out on the how to do an increment each time the button is clicked after the random numbers matches, or doesn't match.
Basically, if the numbers matched, a counter for matched will go up. Same goes for mismatched numbers.
But currently, the counter will only go up once and only once.
jQuery:
$(document).ready(function(){
var a;
var b;
display();
displayInt();
function displayInt(){
var disInt;
disInt = setInterval(display, 2000);
}
function display() {
a = Math.floor((Math.random()*3)+1);
$("#number1").html(a);
b = Math.floor((Math.random()*3)+1);
$("#number2").html(b);
}
function addScore(){
var correct;
var wrong;
correct=0;
wrong=0;
if (a == b){
correct++;
$("#correctScore").html(correct);
}else{
wrong++;
$("#wrongScore").html(wrong);
}
}
$('input[type="button"]').click(function() {
a = $("#number2").html();
b = $("#number1").html();
addScore();
});
});
The value correct is local in the function addScore. It is increased every time, but it is also set to 0 every time. You need to place correct and also wrong outside that function.
var correct = 0;
var wrong = 0;
function addScore(){
if (a == b){
correct++;
$("#correctScore").html(correct);
}else{
wrong++;
$("#wrongScore").html(wrong);
}
}
$(document).ready(function(){
var a;
var b;
var correct = 0;
var wrong = 0;
display();
displayInt();
function displayInt() {
var disInt;
disInt = setInterval(display, 2000);
}
function display() {
a = Math.floor((Math.random()*3)+1);
$("#number1").html(a);
b = Math.floor((Math.random()*3)+1);
$("#number2").html(b);
}
function addScore() {
if (a == b) {
correct++;
$("#correctScore").html(correct);
} else {
wrong++;
$("#wrongScore").html(wrong);
}
}
$('input[type="button"]').click(function() {
a = $("#number2").html();
b = $("#number1").html();
addScore();
});
});

Set Maximum attempts for jquery setTimeOut

I have jQuery code that does some setTimeOut. I want to set maximum attempts that it tries to do the timeout. After "n" attempts it shouldn't time out any more. I looked up a quite a bit but couldn't figure a way. is there a way I can do it.
var qualv = function () {
var isPublish = true;
if (isPublish) {
if ($(".qual_ol_send_box").length) {
PopupLink.init();
} else
setTimeout(qualv, 1000)
}
}
$(document).ready(function () {
setTimeout(qualv, 500)
});
Something like this:
var count = 0;
var MAX_TIMEOUTS = /*yournum*/
var qualv = function(count) {
var isPublish = true;
if(isPublish) {
if($( ".qual_ol_send_box" ).length) {
PopupLink.init();
} else
setTimeout(qualv,1000)
}
$(document).ready(function() {
count ++;
if(count<MAX_TIMEOUTS){
setTimeout(qualv(count),500)
} else {
/* your best */
}
});
}
Then just use while
var qualv = function () {
var isPublish = true;
if (isPublish) {
if ($(".qual_ol_send_box").length) {
PopupLink.init();
} else
setTimeout(qualv, 1000)
}
}
$(document).ready(function () {
var MAX_TIMEOUTS = /*yournum*/
while (i < MAX_TIMEOUTS ) {
setTimeout(qualv, 500);
i++;
}
});

Re-factor jquery function to trigger percentage loader

I have recently downloaded the jquery percentage loader plugin and am trying to refactor some code behind the examples to suit what I need. The code that I have which is working triggers off the percentage loader on click of the run-multiple button...
$().ready(function() {
// Multiple loaders
$("#multiple-loader-container").children().each(function (i) {
var loader = $(this).percentageLoader({width:225, height:225});
$("#run-multiple").click(function () {
var thisLoaderRunning = false;
var totalValue = (i + 1) * 333.0;
var value = 0;
// A function representing a single 'frame' of our animation
var animateFunc = function() {
value += 17;
if (value > totalValue) {
value = totalValue;
}
loader.setProgress(value / totalValue);
loader.setValue(value.toString() + 'kb');
if (value < totalValue) {
setTimeout(animateFunc, 25);
} else {
thisLoaderRunning = false;
}
}
setTimeout(animateFunc, 25);
return false;
});
});
});
function setProgress(value) {
var volumeDb = Math.round(-100.0 + value);
$controllableLoader.setValue(volumeDb + ' db');
}
I am trying to change this to work without buttons and to just trigger the percentage loader after 2 seconds of the page loading. I will post what I have tried but I can't quite get it to work. Just looking for some help.
var progressBarTimer = null;
var progressBarTimerInterval = 2000;
$().ready(function() {
// Multiple loaders
$("#multiple-loader-container").children().each(function (i) {
var loader = $(this).percentageLoader({width:225, height:225});
setTimeout(animateLoaders(null,i), progressBarTimerInterval);
});
});
function setProgress(value) {
var volumeDb = Math.round(-100.0 + value);
$controllableLoader.setValue(volumeDb + ' db');
}
function animateLoaders(value, i) {
var thisLoaderRunning = false;
var totalValue = (i + 1) * 333.0;
var value = 0;
// A function representing a single 'frame' of our animation
var animateFunc = function() {
value += 17;
if (value > totalValue) {
value = totalValue;
}
loader.setProgress(value / totalValue);
loader.setValue(value.toString() + 'kb');
if (value < totalValue) {
setTimeout(animateLoaders, 25);
} else {
thisLoaderRunning = false;
}
}
setTimeout(animateLoaders, 25);
return false;
}
Thanks for the tip in the answer. What I did was to change the code to this...
$().ready(function() {
// Multiple loaders
$("#multiple-loader-container").children().each(function (i) {
var loader = $(this).percentageLoader({width:225, height:225});
var thisLoaderRunning = false;
var totalValue = (i + 1) * 333.0;
var value = 0;
var animateFunc = function() {
value += 17;
if (value > totalValue) {
value = totalValue;
}
loader.setProgress(value / totalValue);
loader.setValue(value.toString() + 'kb');
if (value < totalValue) {
setTimeout(animateFunc, 25);
} else {
thisLoaderRunning = false;
}
}
setTimeout(animateFunc, 25);
});
});
function setProgress(value) {
var volumeDb = Math.round(-100.0 + value);
$controllableLoader.setValue(volumeDb + ' db');
}
You're calling animateLoaders(null,i), but calling that function doesn't return another function, it returns a boolean. But the setTimeout function requires a function to run as its first parameter.
Try changing your call to setTimeout to look like this:
$("#multiple-loader-container").children().each(function (i) {
var loader = $(this).percentageLoader({width:225, height:225});
setTimeout(function() {
animateLoaders(null,i);
},
progressBarTimerInterval);
});

setTimeout on Jquery gallery does not work

I have a gallery that doesnt work properly with setTimeout.
I need to make the gallery change a photo every few sec. but if I press on the indicator, then I want it to change it manually.
this is my js file :
var arrayPic = ["/img/gallery/gal1.jpg",
"/img/gallery/gal2.jpg",
"/img/gallery/gal3.jpg",
"/img/gallery/gal4.jpg",
"/img/gallery/gal5.jpg",
"/img/gallery/gal6.jpg"];
var counter = 0;
var waitTime = 5000;
var transitionTime = 500;
var t;
var time_is_on = 0;
$(document).ready(function () {
t = setTimeout(function() {
changeThisPhoto();
changeIndicator();
}, 1000);
$(".countrydd").ykDropdown();
$(".subjectdd").ykDropdown();
});
function stopTime() {
clearTimeout(t);
time_is_on = 0;
}
function changeDefaultIndicator() {
console.log($("li.active"));
var thisChild = ($("li.active").index(this)) + 1;
for (var i = 0; i < arrayPic.length; i++) {
$("#indi" + i).removeClass();
}
$("#indi" + thisChild).addClass("active");
}
function changeIndicator() {
$(".indicatorslist li").bind("click", function () {
var thisChild = ($(".indicatorslist li").index(this)) + 1;
for (var i = 0; i < arrayPic.length; i++) {
$("#indi" + i).removeClass();
}
$("#indi" + thisChild).addClass("active");
changeThisPhoto(thisChild);
})
}
function animatePhotoOut() {
$(".backgroundImage").animate({
opacity: 1
}, transitionTime, function () {
$(".backgroundImage").delay(waitTime);
changeThisPhoto();
})
}
function changeThisPhoto(child) {
var stepper = 0;
if (!child) {
child = -1;
}
$(".backgroundImage").stop().animate({
opacity: 0
}, transitionTime, function () {
if (counter == 5) {
counter = 0;
} else {
counter++;
}
if (child = -1) {
stepper = counter;
}
else {
stepper = child;
}
$(".backgroundImage").css("background-image",
"url('" + arrayPic[stepper] + "')");
changeDefaultIndicator();
animatePhotoOut();
})
}
it works beautifully when I click the indicator, but won't work with the setTimeout() function... probably...
The setTimeout will only run the change once. Use setInterval instead.

Resources