Javascript number counter with cache - javascript

I have this script for to increment a counter by one after 1 second , but when I refresh the page I need to remember the last number I counted.
Example: Currently, I have 40. When I refresh the page I need to start counting after 40 not reset to 1. Is this possible?
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(obj.innerHTML);
setInterval(function() {
current++;
// Update the contents of the element
obj.innerHTML = current;
}, 1000);
}
animateValue('value');
<h1>
<div id="value">1</div>
</h1>

You can store the counter progress in localStorage, then retrieve the value on page load and start counting from there:
var obj = document.getElementById("value");
let counterStorage = localStorage.getItem('counter')
if(counterStorage) obj.innerHTML = counterStorage
function animateValue(id) {
var current = parseInt(obj.innerHTML);
setInterval(function() {
current++;
localStorage.setItem('counter', current)
obj.innerHTML = current;
}, 1000);
}
animateValue('value');

Use localstorage. If not exists then set and if exists use the value from localstorage.
function animateValue(id){
const obj = document.getElementById(id);
let current = parseInt(obj.innerHTML);
const storageTime = localStorage.getItem("mytime")
if ( storageTime === null) {
localStorage.setItem("mytime", current);
} else {
current = storageTime;
}
setInterval(function(){
current++;
localStorage.setItem("mytime", current);
// Update the contents of the element
obj.innerHTML = current;
},1000);
}
animateValue('value');
<h1><div id="value">1</div></h1>

you can use window.localstorage. the code will look something like this
window.localstorage.setItem('timer', timer)

Related

Save current div id on cookie

I have this code:
$(function games() {
// Different timeouts for each div
var times = [4000, 5000, 5000, 8000, 8000];
var counter = 0;
divs = $('#tuk1, #tuk2, #tuk3, #tuk4, #tuk5');
function showDiv() {
// hide all divs, filter current index, and fadeIn
divs.hide().eq(counter).fadeIn(0);
// set time out duration from array of times
setTimeout(showDiv, times[counter]);
// cycle the counter
counter = (counter + 1) % divs.length;
};
showDiv(); // show first div
});
How could I modify it to save the last DIV viewed by the user on a COOKIE?
I searched for a long time, I do not find, please..
function cssLayout() {
document.getElementById("tuk").href = this.value;
}
function setCookie(){
var date = new Date("Februari 10, 2013");
var dateString = date.toGMTString();
var cookieString = "Css=document.getElementById("tuk").href" + dateString;
document.cookie = cookieString;
}
function getCookie(){
alert(document.cookie);
}
Like that ?

Confused about SetInterval and closures

How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>

Creating a continuous counter with Javascript?

function lemath()
{
var count;
count = 0;
stuff.innerHTML = "stuff" + count;
}
function begin()
{
lemath();
setTimeout(function() {
begin();
}, 1000);
}
I'm trying to create an infinite loop that will count each time it loops and display it, but when I do the code above it just gives back undefined?
Thank you very much with the help! :)
var count = 0; // declaring "count" here makes the variable globally available
function lemath()
{
count++;
var stuff = document.getElementById('stuff');
stuff.innerHTML = "stuff: " + count;
}
function begin()
{
lemath();
setTimeout(begin, 1000, window);
}
document.addEventListener('DOMContentLoaded', function () {
begin();
});
Demo: http://jsfiddle.net/pottersky/jj30s2Le/1/
you can use setInterval javascript method for increase your counter
// setInterval(fn, time);
// your counter state should be start from 0
let count = 0;
// Your function should be run each time (for example each second)
const increment = () => {
count++
// show count in console or in DOM
console.log(count)
element.innerHTML = count
}
setInterval(increment, 1000);
For Performance reason and for stop or reset timer you can use clearInterval method
const timer = setInterval(increment, 1000);
// stop counter
clearInterval(timer)

Countdown timer that refreshes depending on the data I receive by a WebSocket

I want to build a 10-seconds JQuery Countdown-Timer with a WebSocket that refreshes every second. It should reset the timer at x seconds (depending on the data I get from the WebSocket). If I get data for a specific timer, it should start over and counting down from 10s again, but only for this specific timer.
If one of these timers drops to 0, the countdown should stop completely.
At the moment I use setInterval for demonstration reasons, but I want to implement this timers to the WebSocket as mentioned: http://jsfiddle.net/alexiovay/azkdry0w/5/
JavaScript:
var setup = function(){
$('.count').each(eachSetup);
};
var eachSetup = function(){
var count = $(this);
var sec = count.data('seconds') ;
count.data('count', sec);
};
var everySecond = function(){
$('.count').each(eachCount);
};
var eachCount = function(){
var count = $(this);
var s = count.data('count');
count.text(s);
s--;
if(s < 0) {
s = 0;
}
count.data('count', s);
};
setup();
setInterval(everySecond, 1000);
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="count" data-seconds="5"></p>
<p class="count" data-seconds="10"></p>
<p class="count" data-seconds="15"></p>
My WebSocket starts like this and refreshes every second:
var socket = io.connect('http://localhost:8000');
socket.on('notification', function (data) {
$.each(data.rows,function(index,row){
...
If you're getting, say, data.user and data.seconds from the socket, you could do the following:
var timers = []; // Creates an array to store your timers
socket.on('notification', function(data) { // Listen for 'notification' from socket
if(timers.length > 0) {
for(i in timers) {
if(timers[i][0] === data.timer) {
timers[i][1] = 10; // If timer for data.user already exists, set it to 10 seconds again.
} else {
timers.push([data.timer, data.seconds]); // Else, create it with data.seconds seconds
}
}
} else {
timers.push([data.timer, data.seconds]);
}
}
function timerCount() {
for(i in timers) {
if(timers[i][1] <= 0) {
delete timers[i]; // If timer seconds is less than 0, delete it.
} else {
timers[i][1]--; // Else, decrease it by 1 second.
}
}
}
setInterval(timerCount, 1000); // Runs the timerCount() function every second.

Change img src every second using Jquery and Javascript

I have been trying to write a script that changes an image src every two seconds based on a list.
So, everything is inside a forloop that loops over that list:
$(document).ready(function() {
var lis = {{dias|safe}}; <----- a long list from django. This part of the code works fine.
for (i=0; i<lis.length; i++){
src_img = lis[i][1];
var timeout = setInterval(function(){
console.log(src_img)
$("#imagen").attr("src", src_img);
}, 2000)
}
});
It doesn't work, the console logs thousands of srcs that correspond to the last item on the list. Thanks a lot for your help.
you don't need to run cycle in this case, you just save "pointer" - curentImage and call next array item through function ever 2 sec
var curentImage = 0;
function getNextImg(){
var url = lis[curentImage];
if(lis[curentImage]){
curentImage++;
} else {
curentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
var curentImage = 0;
var length = lis.length;
function NewImage(){
var url = lis[curentImage];
if(curentImage < length){
currentImage++;
}
else{
currentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
PS: Better than the previous one, Checks for lis length and starts from first if you reach end.
You need something like this
$(document).ready(function() {
var index = 0;
setInterval(function(){
src_img = lis[index++ % lis.lenght][1]; // avoid arrayOutOfBounds
$("#imagen").attr("src", src_img);
}, 2000)
});

Categories

Resources