javascript too fast when i set setInterval(function() down (or up i guess, speed wise) to 100 or 500 and wont load mypage.php as it doesn't have time i think? don't want to slow counter down either. so is there a php equivalent that can? (with the little number display like this, see jsfiddle) or is there a better javascript counter ? would prefer php, any ideas?
Thanks heaps, any help would be great.
Changed the page link to # as it will freeze things otherwise
http://jsfiddle.net/aEXgB/2/ Also added exit;but didn't help.
<html>
<head>
<script type="text/javascript">
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)>=3000) {
location.href = 'mypage.php';
exit;
}
i.innerHTML = parseInt(i.innerHTML)+1;
}
setInterval(function(){ countdown(); },.75);
</script>
</head>
<body>
<div style="margin-left:20px; float:left;"><p>Countdown:<font color="#33CC00"> <span id="counter">10 </span></font></p></div>
</body>
</html>
replace
setInterval(function(){ countdown(); },.75);
with
var t = setInterval(function(){ countdown(); },.75);
then just before the exit in the function, add;
clearInterval(t);
First, I don't understand why it's called a countdown when you count UP.
Second, I think it's better to update the counter and THEN check the value. That way you don't have an extra call to the coundown function.
Third, clear the interval before changing location because the interval is probably getting fired again too quickly.
Fourth, this won't actually work in jsfiddle because of how jsfiddle uses iframes :)
var interval = setInterval(function(){ countdown(); },.75);
function countdown() {
var i = document.getElementById('counter');
i.innerHTML = parseInt(i.innerHTML)+1;
if (parseInt(i.innerHTML)>=3000) {
clearInterval(interval);
window.location.href = "mypage.php";
}
}
JS:
var sec = 0;
var interval = 750; // milliseconds
var stop = 5; // seconds
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval( function(){
if(document.getElementById("seconds").innerHTML < stop) {
document.getElementById("seconds").innerHTML=pad(++sec%60);
} else {
location.href = 'http://google.nl'
}
}, interval);
Html:
<div id="seconds></div>
Fiddle:
http://jsfiddle.net/5tM3A/5/
Related
can someone please help me with js/ajax countdown i want a countdown timer to 10 sec then update the database and refresh the page once it hits to 0.
i'm not really good with javascript/ajax, here is what i got so far:
var ss = 10;
function countdown() {
ss = ss-1;
if (ss<0) {
var url='update.php?countdown='+countdown;
}
else {
document.getElementById("countdown").innerHTML=ss;
window.setTimeout("countdown()", 1000);
}
}
<span id="countdown" style="color:green;">10</span>
and update.php file, witch works fine:
if (isset($_REQUEST['countdown'])) {
mysql_query("INSERT INTO num (id, ad, active)
VALUES ('1', 'Test',1)") or die(mysql_error());
}
and also this is what i found http://pastebin.com/Qwz3Zqtt , works fine but i don't know how to put them together.
any helps would be appreciated.
Thanks
You're going to want to learn basic ajax to process the database request. jQuery has a very easy to use implementation.
The basic code could be something like:
<script>
function updateTimer(seconds){
var countdown = document.getElementById('countdown');
countdown.innerHTML = "Please wait " + seconds + " seconds.";
}
var timer = function() {
var seconds = 10;
var interval = setInterval(function(){
if (seconds <= 0){
countdown.innerHTML = "Finished.. Updating Database";
// AJAX request here
clearInterval(interval);
}else{
updateTimer(seconds);
--seconds;
}
}, 1000);
updateTimer(seconds);
--seconds;
}
document.getElementById('start').addEventListener('click', timer);
</script>
<div id="countdown"></div>
<button id="start">Click Me</button>
Here's a fiddle
Use jQuery ajax
Simplest example:
if (ss<0) {
$.ajax('update.php?countdown='+countdown);
}
I am trying to follow a jsfiddle example to create a time in javascript:
http://jsfiddle.net/g3rRJ/
Now obviously the timer in the jsfiddle works fine. But the issue I have is that the time which the timer starts from comes for a mysqli/php variable where it retrieves the time from the db.
So except for:
<span id="countdown">01:30:10</span>
I have to have it as:
echo "<p><span id='countdown'>" . $dbSessionDuration . "</span></p>";
AND
except for:
var time = "01:30:10",
I have to have it as:
var time = <?php echo json_encode($dbSessionDuration); ?>,
Now I am getting no errors but what is happening is that the timer is not doing a count down. My question is why is it not counting down? An example of the time from the variable could be 01:00:00.
Below is the code for the function:
echo "<p><span id='countdown'>" . $dbSessionDuration . "</span></p>";
...
<script type="text/javascript">
(function(){
$(document).ready(function() {
var time = <?php echo json_encode($dbSessionDuration); ?>,
parts = time.split(':'),
hours = +parts[0],
minutes = +parts[1],
seconds = +parts[2],
span = $('#countdown');
function correctNum(num) {
return (num<10)? ("0"+num):num;
}
var timer = setInterval(function(){
seconds--;
if(seconds == -1) {
seconds = 59;
minutes--;
if(minutes == -1) {
minutes = 59;
hours--;
if(hours==-1) {
alert("timer finished");
clearInterval(timer);
return;
}
}
}
span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
}, 1000);
});
});
</script>
Change this:
});
});
</script>
to this:
});
})(); // ← note the extra parentheses
</script>
so that you actually call your anonymous function. (Alternatively, you can simply remove its (function(){ and }); entirely. There's no reason for this code to be in a function at all.)
I don't know if this was a mistype but I was able to run this code by adding $, $(function(){, at the first part of your anonymous function. I'm assuming your value from the db comes in as hours:mins:secs. I'm not sure why Fiddler ran but I had to add that to get it to work in my environment.
I have a setTimeout and clearTimeout where the setTimeout is working fine but clearTimeout is not working, can anyone help me?
code:
<script type="text/javascript">
var i = 0;
var status = setTimeout(function () {
if (i <= 2) {
metrics_status();
i++;
} else {
clearTimeout(status);
};
}, 3000);
</script>
<div id="ReloadMetrics"></div>
You should use clearTimeout outside setTimeout like this
var status;
if(status){
clearTimeout(status);
}
status = setTimeout(function () { }
Example1
Example2
I assume you need setInterval instead. which will call your function in specified intervals, until you call the clearInterval
setTimeout function called only once if it is recursive then you need to call clearTimeout
To call a function multiple times then you use setInterval then you can call clearTimeout
Example of setTimeout and clearTimeout is http://www.w3schools.com/jsref/met_win_cleartimeout.asp
Timing functions http://www.w3schools.com/js/js_timing.asp
take a look on the given example http://jsfiddle.net/jogesh_pi/qTGPT/
<div id="status"></div>
JS:
var i = 0;
var status = setInterval(function() {
if (i <= 5) {
//metrics_status();
document.getElementById('status').innerHTML = i;
} else {
document.getElementById('status').innerHTML = "done";
_clearTime();
}
i++;
}, 1000);
function _clearTime(){
return clearInterval(status);
}
hope this should work according to your need..
I think this will do your purpose. please check
<script type="text/javascript">
var i = 0;
var status;
status = setTimeout(Fun, 3000);
function Fun() {
if (i <= 2) {
metrics_status();
i++;
status = setTimeout(Fun, 3000);
} else {
//clearTimeout(status);
};
}
</script>
<div id="ReloadMetrics"></div>
I am using a div refresh script (Given below). The contents of the div contains an auto scroll ul (code from http://www.dynamicdrive.com/). The refresh is working properly. But after the refresh the auto scrolling is not working
Code for refresh
<script type="text/javascript">
window.onload = setupRefresh;
function setupRefresh()
{
setInterval("refreshBlock();",1000);
}
function refreshBlock()
{
$('#list4').load("refreshpage");
}
</script>
Code for auto scroll
<script type="text/javascript">
var delayb4scroll=2000 //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=1 //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=1 //Pause marquee onMousever (0=no. 1=yes)?
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var actualheight=''
function scrollmarquee(){
if (parseInt(cross_marquee.style.top)>(actualheight*(-1)+8))
cross_marquee.style.top=parseInt(cross_marquee.style.top)-copyspeed+"px"
else
cross_marquee.style.top=parseInt(marqueeheight)+8+"px"
}
function initializemarquee(){
cross_marquee=document.getElementById("vmarquee")
cross_marquee.style.top=0
marqueeheight=document.getElementById("list4").offsetHeight
actualheight=cross_marquee.offsetHeight
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
cross_marquee.style.height=marqueeheight+"px"
cross_marquee.style.overflow="scroll"
return
}
setTimeout('lefttime=setInterval("scrollmarquee()",30)', delayb4scroll)
}
if (window.addEventListener)
window.addEventListener("load", initializemarquee, false)
else if (window.attachEvent)
window.attachEvent("onload", initializemarquee)
else if (document.getElementById)
window.onload=initializemarquee
</script>
Could some one please help?
It seems like you need to call initializemarquee() after the load is complete. You can do this in the .load()'s callback.
function refreshBlock(){
$('#list4').load("refreshpage", function(){
clearInterval(lefttime);
initializemarquee()
});
}
I almost forgot to add that you'd also want to stop that interval.
You just need:
function refreshBlock()
{
$('#list4').load("refreshpage");
initializemarquee();
}
Why the mix of plain JS and jQuery? If you have jQuery use it
Here is my rewrite. Not tested but apart from typos or things that I thought could be done in jQuery and cannot, it should do the whole thing
$(function() {
var sId = setInterval(function {
$('#list4').load("refreshpage");
},1000);
var $cross_marquee=$("#vmarquee")
var delayb4scroll=2000 //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=1 //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=true //Pause marquee onMousever (false=no. true=yes)?
var copyspeed=marqueespeed;
var pausespeed=(pauseit==0)? copyspeed: 0;
var actualheight=$cross_marquee.height();
var marqueeheight=$("#list4").height();
$cross_marquee.top(0);
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
$cross_marquee.height(marqueeheight);
$cross_marquee.css("overflow","scroll");
}
else var tId = setTimeout(function() {
lefttime=setInterval(
function() {
var top = $cross_marquee.top();
if (top>(actualheight*(-1)+8)) $cross_marquee.top(top-copyspeed)
else $cross_marquee.top(marqueeheight+8);
}
},30)
, delayb4scroll);
});
I have a pinterest style site and made a jquery script that spaces the cubes evenly no matter how big the browser is. For some reason on page load it has some overlapping cubes which didn't exist before. I talked with the guy that helped me make it and he said it's probly because of the code before the code that creates the blocks and positions them. It crashes the javascript.
I think it's because of the $(window).scroll ajax loading code but I can't seem to pinpoint the problem. I tried moving positionBlocks(); around and nothing changes. If you load the page in your browser and then change your browser size then it positions them correctly but obviously I want it to look right when the user first gets there.
function setupBlocks() {
windowWidth = $(window).width();
blocks = [];
// Calculate the margin so the blocks are evenly spaced within the window
colCount = Math.floor(windowWidth/(colWidth+margin*2));
spaceLeft = (windowWidth - ((colWidth*colCount)+margin*2)) / 2;
spaceLeft -= margin;
for(var i=0;i<colCount;i++){
blocks.push(margin);
}
positionBlocks();
}
function positionBlocks() {
$('.block').each(function(i){
var min = Array.min(blocks);
var index = $.inArray(min, blocks);
var leftPos = margin+(index*(colWidth+margin));
$(this).css({
'left':(leftPos+spaceLeft)+'px',
'top':min+'px'
});
blocks[index] = min+$(this).outerHeight()+margin;
});
}
// Function to get the Min value in Array
Array.min = function(array) {
return Math.min.apply(Math, array);
};
var curlimit=<?php echo $curlimit; ?>;
var totalnum=<?php echo $num_rws; ?>;
var perpage=<?Php echo $perpage ?>;
var working_already=false;
$(document).ready(function() {
//($(window).scrollTop() + $(window).height() )> $(document).height()*0.8
// old ($(window).scrollTop() + $(window).height() == $(document).height())
$(window).resize(setupBlocks);
$(window).scroll(function() {
if(($(window).scrollTop() + $(window).height() )> $(document).height()*0.90 && totalnum>0 && working_already==false ) {
} else return false;
working_already=true;
$("div#loading_bar").fadeIn("slow");
curlimit=curlimit+perpage;
$("div#loading_data_location").html("");
$.get('get_cubes.php?page=<?php echo $_GET['page'] ?>&curlimit='+curlimit, function(response) {
$("div#loading_data_location").html(response);
$("div#ColumnContainer").append($("div#loading_data_location").html());
$("a#bigpic").fancybox({
'onComplete' : imageLoadComplete,
'onClosed' : imageClosed,
'type': 'ajax' });
if ($("div#loading_data_location").text()=="")
totalnum=0;
else
totalnum=<?php echo $num_rws; ?>;
$('.like:not(.liked)').click(like_box);
$('.save:not(.saved)').click(save_box);
$('.follow:not(.following)').click(follow);
$("div#loading_bar").fadeOut("fast");
$("div#loading_data_location").html('');
setupBlocks();
working_already=false;
});
});
I had to add this to the end of my script:
<script language="javascript">
$(window).bind("load", function() {
setupBlocks();
});
</script>
and then this to the end of the on scroll ajax load. Sometimes jquery just needs a little kick in the face haha:
setTimeout(function(){setupBlocks();},100);