How to make this a slow jQuery counter - javascript

I am currently busy with making a new website.
I would like to make a counter on my website that shows visitors how many websites I made.
I am currently using Javascript and jQuery to do this. The only problem is that while using the for loop, the result shows very fast and I would like it to count up slowly. This is the code I have so far:
$(document).ready(function() {
var websites = 10;
for (var i=0;i<websites;i++)
{
$('.webcounter').html(i);
}
});
Any one has an idea to making the counter go slow?

You can try this:
var interval = window.setInterval(func, delay[, param1, param2, ...]);

This timer works in seconds, you can put the code to run after it's complete in the else section:
Javascript
function countdown(count){
$('.webcounter').html(count);
count -= 1;
if(count >= 0)
setTimeout("countdown("+count+")", 1000);
else
alert("Countdown Complete");
}
$(document).ready(function() {
countdown(10);
}
HTML
<div class="webcounter">Webcounter Holder</div>​
Demo
http://jsfiddle.net/silver89/SBXAQ/8/

Use setInterval:
EXAMPLE
HTML
​<div class="websites">0</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​
JQUERY
$(document).ready(function() {
var websites = 10;
var counter = 1;
var id = setInterval(function(){
$('.websites').text(counter);
counter++;
if(counter > websites){ clearInterval(id);}
}, 500);
});​

Just a quick guess, but try something like this (i'm at work and cant test myself, heheh)
var websites = 10, tmrSiteCount;
function siteCount(i) {
if (i <= websites) {
$('.webcounter').html(i);
tmrSiteCount = setTimeout(function() { siteCount(i++); }, 1000);
}
else {
clearTimeout(tmrSiteCount);
};
}
$(document).ready(function() {
tmrSiteCount = setTimeout(function() { siteCount(1); });
})

Related

Why does setInterval() stop too early in this code?

<div class="wait">Wait</div>
<div class="waitDownloadLink"></div>
$(document).ready(function()
{
var secondNormal = 40;
var refreshIntervalId;
refreshIntervalId = setInterval(function() {
secondNormal -= 1;
$(".wait").text(secondNormal);
}, 1000);
setTimeout(function() {
clearInterval(refreshIntervalId);
$(".waitDownloadLink").text("Click me to download");
}, secondNormal * 1000);
});
When I start running the code and stay on the webpage, the code seems too work perfectly (or nearly). However, when I surf on other webpage right after I started the code, the timer is stuck between 12 - 18 second and then stops running. Why does this happen? And is there any solution to solve this?
https://jsfiddle.net/s1zf18co/
Browsers typically pause or reduce thread priority for Javascript running in tabs that aren't visible. My guess is that it's a power saving measure for laptops and other things, but they all have done this for years now. This question has an incredibly thorough investigation into the issue.
The solution is to use web workers which don't get paused. See the Mozilla documentation for more information.
I cannot seem to replicate the bug, however I believe that using the Date object may fix it:
var getDateTimeInSeconds = function() {
return Math.floor(Date.now() / 1000)
};
$(document).ready(function() {
var numOfSeconds = 40;
var countFrom = getDateTimeInSeconds();
var countTo = countFrom + numOfSeconds;
var refreshIntervalId = setInterval(function() {
var secondsLeft = countTo - getDateTimeInSeconds();
if (secondsLeft < 0) {
$(".wait").text(0);
$(".waitDownloadLink").text("Click me to download");
clearInterval(refreshIntervalId);
} else {
$(".wait").text(secondsLeft);
}
}, 1000);
});
Fiddle: https://jsfiddle.net/s1zf18co/1/
there is one working solution, try this and c if it is good enough, it is ok with leaving page problem, edit on end condition.
$(document).ready(function () {
var secondNormal = 40;
var refreshIntervalId = setInterval(function () {
setTimeout(function () {
if(secondNormal >0) {
secondNormal -= 1;
}
}, 1000)
$(".wait").text(secondNormal);
}, 1000);
});
Aside from Mordred's answer, in this case you may try using JS Date object to correctly estimate time. Check out this question.

jQuery setInterval too fast when tab is inactive

When the tab my website is on is inactive, my slideshow starts switching pictures too fast and mess the whole thing up.
Is there a way i could fix this?
var img_src = ["1.png", "2.png", "3.png", "4.png"];
var delay = 8000;
var first_run = true;
function switch_pic(position){
$("#show").attr("src", img_src[position]).fadeOut(0).fadeIn(4000).fadeOut(4000);
}
$(document).ready(function(){
var i = 0;
if(first_run){
switch_pic(i);
first_run = false;
i++;
}
window.setInterval(function(){
switch_pic(i);
delay += 8000;
i++;
if(i > 3){
i = 0;
window.clearInterval();
}
}, delay);
});
Could wrap the code in this:
$(document).ready(function(){
$([window, document]).focusin(function(){
//code run when tab is selected
}).focusin(function(){
//code to stop all animation
});
});
That would only let the slideshow run when the user is viewing your site.
I'm not sure why things speed up. Normally the timers on background tabs will be slowed down to at least one second, but this shouldn't affect your scenario. I suggest using console.log() to track the calls to your functions.
Also, you can simplify your main loop a bit:
$(document).ready(function(){
var i = 0;
window.setInterval(function(){
switch_pic(i++); // increase i after call
if(i > 3) i = 0; // reset i
}, 8000);
});
I think that the answer good for actual version of jQuery should look like this:
var intervalId;
$([window, document]).on('focusin', function(){
intervalId = setInterval(function() {
// Action in interval
}, 3000);
}).on('focusout', function(){
if (intervalId) {
clearInterval(intervalId);
}
});
Pleas remember, that first time your 'focusin' is not tigger when page is loaded, so you should use this construction for this:
intervalFunction();
$([window, document]).on('focusin', function(){
if (!intervalId){
intervalFunction();
}
}).on('focusout', function(){
if (intervalId) {
clearInterval(intervalId);
intervalId = undefined;
}
});
function intervalFunction() {
// Your function hire
}

Multiple Timers in Quiz with jQuery

I'm on a quiz, where you can pick an answer out of four answer possibilities (like who wants to be a millionaire). I want to add a counter of 7secs per question to it, if the counter ends, a button to the next question should appear.
I already have my basic code with jQuiz, but my problem is now, that I use always the same counter instance. So the timer of the first question is fine, but if you answer the next question and have some time left of the first one, both counters are displayed at the same time. I think my problem will be solved when I have multiple timer instances, but I don't know how to do this.
Here my code. Sorry about the bad structure, I'm a jQuery newbie.
$('.btn, .nxt').click(function(){
$(this).addClass("checked");
next(this);
var el = $('#progress');
el.width(el.width() + 116 + 'px');
});
function next(elem){
$(elem).parents('.questionContainer').fadeOut(300, function(){
var interval = window.setInterval(function() {
var counter = 0;
clearInterval(interval);
});
var counter = 0;
timer();
$(elem).parents('.questionContainer').next().fadeIn(300);
$('.nxt').hide();
});
};
function timer(){
var counter = 7;
var interval = window.setInterval(function() {
counter--;
$(".counter").html(counter);
if (counter == 0) {
$(".counter").html('');
$('.nxt').show();
clearInterval(interval);
}
}, 1000);
};​
I'm new at Stackoverflow and it's too hard for me to edit code in this textarea... Added fixed JS to jsfiddle.
Try to add your HTML to the same fiddle and test JS, hope it would work.
There are some fixes about structure (caching selections mostly) and added array for timers (with comments) you were asking for.
It'll be easier to debug when you add HTML :)
var quizObj = {
quizTimers: [], //timers array
$counter: $(".counter"),
$buttons: $('.btn, .nxt'),
$progress: $('#progress'),
next: function(elem){
$(elem).parents('.questionContainer').fadeOut(300, function(){
//clears the FIRST timer id in the timers array and removes it from array
clearInterval(quizObj.quizTimers.shift());
quizObj.timer();
$(elem).parents('.questionContainer').next().fadeIn(300);
$('.nxt').hide();
});
},
timer: function() {
var counter = 7;
var interval = window.setInterval(function() {
counter--;
$(".counter").html(counter);
if (counter == 0) {
$(".counter").html('');
$('.nxt').show();
clearInterval(interval);
}
}, 1000);
quizObj.quizTimers.push(interval);
}
}
quizObj.$buttons.click(function(){
$(this).addClass("checked");
quizObj.next(this);
quizObj.$progress.width(quizObj.$progress.width() + 116 + 'px');
});

Simple JS timer using JS Fiddle

This may not be the place for this question, but here goes anyways.
I am trying to learn more about the JS timers and am using the JS Fiddle for this purpose. In my script, I am using a script that binds functionality to a few elements, but I need the JS Fiddle to not execute it until the page loads completely due to it needing all elements to be initialized and available (see my fiddle at: http://jsfiddle.net/radi8/W2b2M/4/). This fiddle is a VERY rough skeleton.
The format of the script is as follows:
How can I make the JS Fiddle only load this after all other elements are finished?
$(document).ready(function() {
var tmr = {
init: function(){
},
somefunct1: function(){
},
somefunction2: function(){
}
};tmr.init();
});
Any help is appreciated.
document.ready() is the way to good. However, there are other issues with your code. This function is not defined correctly:
function stopTimer {
clearInterval(timer);
}
Should be:
function stopTimer() {
clearInterval(timer);
}
Also, startstop.value is not defined. What is startstop suppose to be?
Update
Your use of .val() is incorrect, and many other issues (fixed):
http://jsfiddle.net/W2b2M/17/
Check this Fiddle:
A simple Javascript Function to Set timer.
$(document).ready(function () {
var input = 120;
function calculateTime(timer) {
var timer = timer;
var mins = Math.floor(timer / 60);
var secs = timer % 60;
var time = (mins < 10 ? "0" : "") + mins + ":" + (secs < 10 ? "0" : "") + secs;
return time;
};
setInterval(function () {
data = calculateTime(input)
if (input > 0)
{
$("#timer").text(data);
input--;
}
else
{
$("#timer").text("Time Out, Njoy Coding in JavaScript")
}
}, 1000);
});
http://jsfiddle.net/MUMU1987/sUkjj/

Hide download link for 10 seconds? js

hey, how can I have my download link hidden, and make a count down type thing. Maybe have it count down from 10 and once it's done that have the download link appear, it would be best to do it in js right?
does anyone know how to do this? :D
Thanks
Complete example:
<span id="countdown"></span>
<a id="download_link" href="download.zip" style="display:none;">Download</a>
<noscript>JavaScript needs to be enabled in order to be able to download.</noscript>
<script type="application/javascript">
(function(){
var message = "%d seconds before download link appears";
// seconds before download link becomes visible
var count = 10;
var countdown_element = document.getElementById("countdown");
var download_link = document.getElementById("download_link");
var timer = setInterval(function(){
// if countdown equals 0, the next condition will evaluate to false and the else-construct will be executed
if (count) {
// display text
countdown_element.innerHTML = "You have to wait %d seconds.".replace("%d", count);
// decrease counter
count--;
} else {
// stop timer
clearInterval(timer);
// hide countdown
countdown_element.style.display = "none";
// show download link
download_link.style.display = "";
}
}, 1000);
})();
</script>
You can use setInterval for this. setInterval behaves like a timer, where you can run a certain function periodically. Something like this should do the work(untested):
$(".link").hide();
var iteration = 0;
var timer = setInterval(function() {
if(iteration++ >= 10) {
clearTimeout(timer);
$(".link").show();
$(".counter").hide();
}
$(".counter").text(10 - iteration);
}, 1000);
This will initially hide the download link and run a function every second which counts down from 10. When we reaced ten, we hide the counter and show the link. ClearTimeout is used so that we don't count after we reached ten. Easy as dell.
Edit: As mentioned in the comments, this function is using jQuery to find the elements.
Take a look at the setTimeout function. You can do something like:
function displayLink() {
document.getElementById('link_id').style.display = 'block';
}
setTimeout(displayLink, 10000);
var WAIT_FOR_SECONDS = 10;
var DOWNLOAD_BUTTON_ID = "btnDownload";
if (document.body.addEventListener) {
document.body.addEventListener("load", displayDownloadButton, false);
} else {
document.body.onload = displayDownloadButton;
}
function displayDownloadButton(event) {
setTimeout(function() {
_e(DOWNLOAD_BUTTON_ID).style.display = "";
}, WAIT_FOR_SECONDS*1000);
}
function _e(id) {
return document.getElementById(id);
}

Categories

Resources