I am using below snippet to load a page content in #load div
var auto_refresh = setInterval(function() {
$('#load').load('load.php?_=' +Math.random()).fadeIn(3000);
}, 10000); // refresh every 10000 milliseconds
It loads pages after each 10 seconds.
Now come to the point what i want. I have five pages.
I need to set loop that autoload pages in every 2 minutes. And so on and at the end it starts from the beginning.
please help me to make this give me some ideas.
Thanks in advance
You haven't told me the format for your pages so I'm assuming you can use numbers to simply count up.
var seed = 0;
var lastPageNumber = 10;
setInterval(function() {
$('#load').load('load.php?page=' + seed + '_=' + Math.random()).fadeIn(3000);
if(seed === lastPageNumber) {
seed = 0;
}
seed++;
}, 120000); // refresh every 120000 milliseconds (120 seconds -> 2 minutes)
Try this:
var i = 0;
var loadPage = setInterval(function() {
$('#load').load('page'+(i++) + '.php').hide().fadeIn(3000);
}, 2000); //---------^^^^^^^^^^^^^^^^^^^----page with number and extension
if(i >= 5){
clearInterval(loadPage);
}
Related
On my website, I am trying to count (and display) how many seconds (not minutes or hours) the user has been on my site. So, if they have been on it for 5 minutes, it will display 300, Not 5 minutes.
I am Very Unexperienced with JavaScript, So please help.
You can use the setInterval function to run another function as often as you choose. For example:
var seconds = 0;
var el = document.getElementById('seconds-counter');
function incrementSeconds() {
seconds += 1;
el.innerText = "You have been here for " + seconds + " seconds.";
}
var cancel = setInterval(incrementSeconds, 1000);
<div id='seconds-counter'> </div>
If you run this snippet, you'll see the counter working.
The setInterval function takes two parameters:
the function you want to call
the number of milliseconds between calls
Since you want to call increment the counter every second, you want to use 1000 milliseconds (1 second).
For more details, see the MDN documentation for setInterval.
My answer is similar to the one above but I'll give it anyway. This will only work on a single page so hopefully your site already runs on AJAX.
window.setInterval((function(){
var start = Date.now();
var textNode = document.createTextNode('0');
document.getElementById('seconds').appendChild(textNode);
return function() {
textNode.data = Math.floor((Date.now()-start)/1000);
};
}()), 1000);
You've been on this page for <span id=seconds></span> seconds.
I have the number 3,453,500 it needs to increase by +1 every 4 seconds.
Need to keep the formatting the same (commas in the right place)
(also is there a way that this can count continuously without the refreshing to the lowest number on page refresh?)
Should be pretty simple...
Retrieve the number from local storage and display it
var num = +localStorage.getItem('num') || 3453500;
document.getElementById('display').innerHTML = num.toLocaleString();
Setup an interval to update the number every 4 seconds, save it and display it
setInterval(function() {
num++;
document.getElementById('display').innerHTML = num.toLocaleString();
localStorage.setItem('num', num);
}, 4000);
JSFiddle
I am trying to use multiple stop watch timer by using anchor tag.I have successfully done but I am not able to add a functionality like if I clicked first timer,It will start timer from zero,when I clicked second one,first timer's value will be zero and second one will start timer from zero.I am giving my working code below :
JS:
var digit=0;
var hrs = 0;
var min=0;
var time;
var timer_is_on=0;
var id;
function timer(id){
//[Old] - this should be placed after you increment digit
// document.getElementById("secs").innerHTML = digit
//alert("I am testing value"+id);
//[New]
// get the numerical value for seconds,minutes,hours
digit = parseInt(document.getElementById("secs"+id).innerHTML);
min = parseInt(document.getElementById("mins"+id).innerHTML);
hrs = parseInt(document.getElementById("hrs"+id).innerHTML);
// increment;
digit=digit+1;
if(digit>"59"){
min = parseInt(min)+1;
// why is this code here
var count = min.toString().length;
digit=0;
}
// [old] checking if second is greater than 59 and incrementing hours
// if(digit>"59"){
// [new] check if minute is greater than 59
if(min > "59"){
hrs=parseInt(hrs)+1;
digit=0;
min=0; // minute should be reset as well
}
// set the values after all processing is done
document.getElementById("secs"+id).innerHTML = format(digit);
document.getElementById("mins"+id).innerHTML= format(min);
document.getElementById("hrs"+id).innerHTML=format(hrs);
}
function activate(id){
if(!timer_is_on){
timer_is_on=1;
// time = setTimeout("timer()",1000) will only call it once , use setInterval instead
time=setInterval("timer("+id+")",1000);
}
else {
timer_is_on=0;
clearInterval(time); // clear the timer when the user presses the button again and reset timer_is_on
}
return id;
}
// left pad zero if it is less than 9
function format(time){
if(time > 9)
return time;
else return "0"+time;
}
And The HTML code I have used are :
Click here to start the timer
<span id="hrs1" >00</span>:<span id="mins1" >00</span>:<span id="secs1">00</span></strong>
<br/>
Click here to start the timer
<span id="hrs2" >00</span>:<span id="mins2" >00</span>:<span id="secs2">00</span>
Here is my working js fiddle demo : http://jsfiddle.net/EPtFW/1/
as you are using same method activate() to start second timer, it will make first timer as zero if timer already running.
Solution is "you have to maintain multiple unique timer ids for multiple timers"
For Example, let's say you have T1 and T2 timers to start time;
var timerMap={};
timerMap[createUniqueId for T1] = setInterval();
timerMap[createUniqueId for T2] = setInterval();
to clear timers
clearInterval(timerMap[createUniqueId for T1]);
clearInterval(timerMap[createUniqueId for T2]);
In your case, you have to have createUniqueId and adding to timerMap should be in activate() method. they will work independently.
what I am trying to do is give the user a textarea (with enabled input) and allow him to write up to 10 chars. Actually, the textarea should ALLOW more chars, not only 10, and the other chars would behave accordingly:
1º There is a setTimeout whenever the user is on the 11ºchar. So, I'm writing something there, I reach the char number 10º (the "maximum" allowed of text) and want that other char to be erased AFTER a given time.
somethinge = 10 chars.
anotherwor = 10 chars.
input: somethingeiefjaiehf
after 5 seconds:
input: somethinge
input: anotherwordtotestthisandseeifitworks
after 5 seconds:
input: anotherwor
2ºTo accomplish this I basically attached a clearTimeout to a global variable:
//Function "countChar(val)" is activated with the keydown event
var timer_to_op = null;
function countChar(val) {
var len = val.value.length; //lenght of input in textarea
clearTimeout(timer_to_op);
//...
//irrelevant code
//...
}else if(len > 140){
$("#status_toOp_num").text(145-len);
timer_to_op = setTimeout(function(){
val.value = val.value.substring(0, 140);
},5000);
}
Actually, for some reason, it won't work. If the user is typing AND he types another char within the 5 seconds then I want the timer to restart.
input: anotherwor
input: anotherword (+d) timer = 1...2...3...
input: anotherworde (+e) timer = 1...2...
input: anotherwordef (+f) timer = 1...2...3...4...5!
input: anotherwor the user took more than 5 seconds so it erased the excedent.
Hope I got my point through. Any ideas on this one? Thank you very much! (I didn't put any html, it's only <textarea onclick="countChar(this)"> )
I didn't really try to understand what you are doing in your code, seems unnecessarily complicated.
Check this fiddle out. http://jsfiddle.net/Q2h5f/
HTML
<textarea id="limitText">0123456789</textarea>
Javascript
var tarea = document.getElementById("limitText");
tarea.onkeypress = checkInputText;
var timer = null;
function checkInputText(e) {
if (timer) clearTimeout(timer);
timer = setTimeout(limitTextLength, 5000);
}
function limitTextLength() {
var tareaVal = document.getElementById("limitText").value.toString();
if (tareaVal.length > 10) {
tarea.value = tareaVal.slice(0, 10);
}
}
Should solve your issue.
I'm attempted to add leading zeros to the seconds value and I keep running into errors. I've tried a number of selected solutions posted here and can't seem to make it work.
I'm pulling values from the spans because those values are coming from the database.
var timer = $('.timer');
$('.prev-button,.next-button').hide();
setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (m.length == 0 && parseInt(s.html()) <= 0) {
timer.html('Proceed to the Next Slide');
$('.prev-button,.next-button').fadeIn();
}
if (parseInt(s.html()) <= 0) {
m.html(parseInt(m.html() - 1));
s.html(60);
}
if (parseInt(s.html()) < 10) {
$('.sec').prepend(0)
}
if (parseInt(m.html()) <= 0) {
timer.html('Time remaining for this slide - <span class="sec">59</span> seconds')
}
s.html(parseInt(s.html() -1));
}, 1000);
http://jsfiddle.net/certainstrings/a2uJ2/1/
I've modified your Fiddle to make it work. http://jsfiddle.net/a2uJ2/3/
You should store the time in javascript int vars instead of reading it from the html elements every time. This causes maintainability problem as you are attaching logic to the layout of your html document.
I haven't fixed all your code but i've created two variables that are used to perform the calculations instead.
Couple of things: You'd be better off registering a start time, and comparing against that inside the interval function. Timers are not guaranteed to be precise, but will instead trigger on or after the interval you specify. If the computer's busy, the timer might be late.
Also, if you're using parseInt, always, always specify a radix argument (the number base). If you don't, the string "08" will will be parsed to "0" because a leading zero is intepreted as an octal (base-8). So use parseInt(string, 10) to parse to a normal base-10 number.
As for adding the leading zero, I'd say you should keep a couple variable for total amount of seconds, rather than reading/writing to the elements all the time.
Updated you jsfiddle
var duration, startTime, interval;
duration = parseInt($(".min").text(), 10) * 60 + parseInt($(".sec").text(), 10);
startTime = (new Date()).getTime();
function countDown() {
var elapsed, remaining, m, s;
elapsed = ((new Date()).getTime() - startTime) / 1000;
remaining = duration - elapsed;
if(remaining <= 0) {
clearInterval(interval);
$(".timer").text('Proceed to the Next Slide');
$('.prev-button,.next-button').fadeIn();
} else {
m = String(Math.round(remaining / 60));
s = String(Math.round(remaining % 60));
if( s < 10 ) {
s = "0" + s;
}
$(".min").text(m);
$(".sec").text(s);
}
}
interval = setInterval(countDown, 500);
This is just a minimal change from you code. I'd probably do something fundamentally different to keep the markup and JS as separate as possible, and so on and so forth, but this works too.
try it like this:
if (parseInt(s.html()) < 10) {
$('.sec').val('0' + $('.sec').val());
}
You're going to need to treat the value as a string rather than as an int. JavaScript is pretty aggressive about converting things that look like numbers into numbers, and that's what's happening here.