Countdown in seconds: milliseconds [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need a div's text to turn red when you start counting, it should lasts 3 seconds and leave the red text while counting. Then return back to normal when it finishes (and regular displays when stopped 3 seconds)
Displaying the count in milliseconds.
I tried, but it still fails.

Something like this?
var foo = document.getElementById('foo');
function startCountDown(ele) {
ele.origText = ele.innerHTML;
ele.style.color = "red";
ele.timeStart = (new Date()).getTime() + 3000;
ele.intervalVar = setInterval(function() {
var curTime = ele.timeStart - (new Date()).getTime();
if(curTime < 0) {
ele.innerHTML = ele.origText;
ele.style.color = "";
clearInterval(ele.intervalVar);
}
else ele.innerHTML = curTime;
},20);
}
setTimeout(function() {startCountDown(foo);},1000);
<div id = 'foo'>bar</div>

Innovative/Alternative way to show timers using requestAnimationFrame,
http://jsfiddle.net/wjtkr95t/4/
wich has less impact to the browser's memory.It also allows you with some minor modifications to have more control over timers,animations ... whatever...
var
end,
now=Date.now,
raf=window.requestAnimationFrame,
duration=120000,//MS
out=document.getElementById('out');
function displayTime(){
var c=end-now();
out.textContent=ms2TimeString(c>0?(raf(displayTime),c):0);
}
function go(){
end=now()+duration;
raf(displayTime);
}
Ms to timeString function
function ms2TimeString(a,k,s,m,h){
return k=a%1e3,
s=a/1e3%60|0,
m=a/6e4%60|0,
h=a/36e5%24|0,
(h?(h<10?'0'+h:h)+':':'')+
(m<10?0:'')+m+':'+
(s<10?0:'')+s+'.'+
(k<100?k<10?'00':0:'')+k
}
https://codereview.stackexchange.com/q/45335/33435
DEMO
http://jsfiddle.net/wjtkr95t/
DEMO (change the color) .. only 100ms.. change it
http://jsfiddle.net/wjtkr95t/1/
DEMO (change the color after 2 sec) .. only 100ms.. change it
http://jsfiddle.net/wjtkr95t/2/
DEMO (change the color after 2 sec with 700ms color animation)
http://jsfiddle.net/wjtkr95t/3/
if you have any questions just ask

I think if you show us your algorithm it would be clearer for anyone who want to help you. Waiting it, I would recommend you to see how the function setInterval() works, because it puts a delay so you probably would use it to reach your goal.
Go here to see docs.

This could be done using CSS animations, and adding a class to a div element.
This method would be better, since CSS animations are not blocking, whereas since javascript is single synchronous thread (for the most part); and so using setInterval will block the rest of the javascript from functioning.

Related

Counting up using jquery

So far I have a little script that detects the scroll top position and at a set level I want it to trigger a jquery counter. So far I have an array with the maximum number inside var = eightyS = [3]; then there is..
if (y > 630) {
$('.targetS').each(function() {
//counter
delay(1000);
});
} else {
return false;
}
Now I've made something similar in C++ years ago (couldn't do it now with a gun to my head) so I followed a similar logic. But this is where I'm stuck. The idea behind this function is that it will do a read out on screen of 0 then 1 then 2 then 3. Any help is greatly appreciated
You could use a setInterval() which executes a function ever second such as below:
var count = 0;
var interval = setInterval(function(){
count++;
$('#counter').text(count);
}, 1000);
I've created a quick JSFiddle
You should be able to wrap this in to your code fairly easily. You may also want to use clearInterval(interval) to stop the function executing when you scroll back up the page; or when you get in to your else block, which would have the same effect. I've added a clearInterval() example to the JSFiddle on click of the stop link. You'll need to make sure the interval variable is in scope when clearing it.

setInterval 'stacking' up [duplicate]

This question already has answers here:
javascript animation queueing when page does not have focus
(3 answers)
Closed 8 years ago.
Using setInterval to run a function which gives a 'flash' effect to a list.
If I keep the page open, but visit another tab / come back in 10 minutes or so, the setInterval feels like its working every 1 seconds as the function is constantly being called.
Feels to me like its stacking up over time, anyway to fix this?
function flashListItems(){
$('.imageview_navigation li').each(function(i) {
$(this).delay((i++) * 100).fadeTo(200, 0.8).fadeTo(200, 1);
});
}
setInterval(function(){
flashListItems();
}, 10000);
fiddle: http://jsfiddle.net/6w6wrsm0/
There's nothing wrong with your code, some web browers slow these types of intervals down to not cause too much usage. So when the webpage is not used, the fastest a interval can go is usually about 1 sec.
There might be a way to fix this, which is mentioned here:
How can I make setInterval also work when a tab is inactive in Chrome?
Just make your animation function tick by real elapsed time.
var div = $('#my-div');
var leftValue = 0;
var interval = (1000/20); //20fps
var before = new Date();
setInterval(function()
{
now = new Date();
var elapsedTime = (now.getTime() - before.getTime());
if(elapsedTime > interval)
{
//Recover the motion lost while inactive.
leftValue += Math.floor(elapsedTime/interval);
}
else
{
leftValue++;
}
div.css("left", leftValue);
before = new Date();
}, interval);

which solution is best performance wise [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am building a small game in javascript to learn object oriented programming in javascript. In it, units move around and do basic stuff.
Animations happens every 20 millisecond. Collision detection should happen every 100 millisecond.
It seems to be faster to have a single setInterval running in the document, as compared to a new setInterval every time a unit is instantiated. So I am doing this. Source: http://www.schillmania.com/content/projects/javascript-animation-2/.
But now I have to do collision detection, as well as animation. I see two solutions:
Solution 1:
window.setInterval(AnimateFunc,20);
function AnimateFunc(){
for (i = 0; i < UnitArray.length; i++){
UnitArray[i].Behaviour(); // Every unit in my array of units behaviour function is called. ex: add 2 pixels to unit.style.top.
}
CollisionDetectionCounter += 1; // Globale variable
if (CollisionDetectionCounter === 5){
CollisionDetectionFunc();
CollisionDetectionCounter = 0;
}
}
With this solution the single setInterval call in the document is preserved. But every second 50 variable incrementations and 50 comparisons is made.
Solution 2:
window.setInterval(AnimateFunc,20);
window.setInterval(CollisionDetectionFunc, 100);
function AnimateFunc(){
for (i = 0; i < UnitArray.length; i++){
UnitArray[i].Behaviour();
}
}
function CollisionDetectionFunc(){
// Perform collision detection between all units curently on the field.
}
With this solution we prevent the 50 incrementations/comparisons but there is now two setInterval functions in play.
So which solution would be best, do you think?
I realize it probably won't matter much. I will probably make other decisions that will screw my game up way worse performance wise down the line, but I am curious :)
Thank you in advance.
Unless those exact timing constraints are your hard limits, I would suggest requestAnimationFrame instead of setInterval. But if you must use setInterval, then I would recommend an approach that's a hybrid of your two setups:
function AnimateFunc(){
for (i = 0; i < UnitArray.length; i++){
UnitArray[i].Behaviour();
}
}
function CollisionDetectionFunc(){
// Perform collision detection between all units curently on the field.
}
function TickFunc() {
AnimateFunc();
CollisionDetectionCounter += 1; // Globale variable
if (CollisionDetectionCounter === 5){
CollisionDetectionFunc();
CollisionDetectionCounter = 0;
}
}
window.setInterval(TickFunc, 20);
This lets you control things off of a single timer. That's not so much a performance concern as a syncing concern: multiple timers can drift relative to one another, and it doesn't sound like you want this to happen. But it also lets you maintain separation of concerns: there's a function for animation, a function for collisions, and a function that coordinates them.
This can also be adapted to use requestAnimationFrame.
You should use requestAnimationFrame instead, for more Information see:
CSS-Tricks
MDN
requestAnimationFrame for Smart Animating
Your code could look similar to this:
var lastCollisionDetection;
var requestId;
function animate(time) {
if (lastCollisionDetection + 100 > time) {
lastCollisionDetection = time;
// TODO: collision detection
}
// TODO: update objects - you might want to check the passed time here as well
requestId = window.requestAnimationFrame(animate);
}
lastCollisionDetection = window.performance.now();
requestId = window.requestAnimationFrame(animate);

jQuery Color Cycle on a href links (Maximum call stack size exceeded and Firefox Issues.)

I'm attempting to make a page that will animate the a href links through a table of colors nice and smoothly. I currently have 2 problems with the code that I'm using experiencing a whole mix of problems relating to bad code (please note that JavaScript and jQuery I'm pretty damn weak at). I'm hoping that some Guru can spend 2mins and let me know what the problem or supply a better solution. (thanks in advance.).
Problems Encountered:
Uncaught RangeError: Maximum call stack size exceeded
Firefox is not smooth while Chrome is (Firefox just changes color).
Some hues are too dark
Performance seems an issue, maybe this is because of the Maximum stack size error
Libraries:
jQuery.v1.10.2.min.js
jQuery.color-2.1.0.js
Code:
jQuery(document).ready(function() {
spectrum();
function spectrum(){
var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
jQuery('body a').animate( { color: hue }, 2000);
spectrum();
}
});
What I need:
Basically all I need is a script that will animate all links on the page from one color to another every 2seconds or more... smoothly. Ideally, I'll like to be able to select 6 or more colors that I know that work but due to my limited knowledge in JavaScript I don't know where to begin.
JSFiddle of the Code in Action
I've made a jsfiddle to hopefully save anyone time or just check what the current output looks like: http://jsfiddle.net/ebZ3x/
Yeah, you're recursively calling indefinitely which will quickly run you out of stack space. What you want instead is for the browser to regularly call your color changing function. We'll use window.setInterval() to accomplish that.
Then we'll also create an array of the six colors you want and we'll just randomly index into it. To add more colors just add them to the array.
jQuery(document).ready(function() {
function spectrum(){
var colors = [
'rgb(256,0,0)', //red
'rgb(0,256,0)', //green
'rgb(0,0,256)', //blue
'rgb(256,256,0)', //orange
'rgb(256,0,256)', //magenta
'rgb(0,256,256)']; //cyan
var hue = colors[(Math.floor(Math.random() * colors.length))];
jQuery('body a').animate( { color: hue }, 2000);
}
var intervalId = window.setInterval(spectrum, 2000);
});
I've been working on your question since you posted it yesterday, and I thought I would give it a shot so I might learn a little about setTimeout. And boy, have I learned - about the complexity of such a "simple" command. It's probably the most difficult I've encountered in javascript.
So I present my "answer" just as something to be viewed, with JoeClacks' answer obviously superior.
This FIDDLE shows the initiation of the timer (runmytimer) after loading the DOM. It changes the background color of two divs randomly. I've let it run for over an hour and it seems not to crash.
I added the "extra" stuff to make sure other things on the page don't interfere with the timer. So when you type into an input box, the timer continues. When you click the "save" button (I just moved the input text to another div) the timer continues.
Here is the relevant JS
var randomcolors = ['#FF00FF','#00FFFF','#FFFF00','#0000FF','#00FF00','#FF0000','#000000','#C0C0C0','#C0C1C1','#CFCHCH','#CCFFCC'];
var timer;
//var timer_is_on = 0;
runmytimer();
$('#saveme').click(function(){
var moveme = $('#getme').val();
$('.movemehere').html(moveme);
});
function runmytimer()
{
t = setTimeout( function(){ runmytimer() }, 1000 );
random = Math.floor(Math.random() * (11 - 0 + 1)) + 0;
$('.putmehere1').css('background-color', randomcolors[random]);
$('.putmehere2').css('background-color', randomcolors[random+1]);
}
For other noobs such as myself who are reading this, I've learned a few things that aren't clearly stated in any documentation (I went to 30-40 sites, that weren't really that helpful).
If you try to put a timer in a loop - its behavior is NOT intuitive. I'm used to BASIC loops where when you do something to STOP the loop - oddly - it STOPS! :-). Not so with javascript. As an experiment I did a loop with a setTimeout in it, and put the i's of the loop in a div. What chaos! The loop printed out all the i's before the first setTimeout was done! I read that the loop is actually creating a different timer for each loop of the setTimeout. Disaster!
You can stop a timer with clearTimeout(nameoftimer).
I'm guessing if you have a routine that stops a timer, it could be restarted at the bottom of the routine with setTimeout(nameoftimer).
I still haven't figured out why a variable assignment such as var timer = setTimeout ( alert('hello'), 1000 ); would not only assign the variable to the code, but also run the code. Not intuitive.
After going to all the sites and trying their code, I went to W3Schools (not held in high esteem by many) and found code that actually worked! I derived my fiddle from that.
Anyway, thanks for the question. I learned a lot!

how to stop moving background-image position

I've background image and by using small javascript code, it moves from right to left.
HTML code
<div id="clouds_image"></div>
Javascript code
var g=0;
var speed=30;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
scroller=setTimeout(function(){rollClouds()},speed);
}
window.addEventListener?
window.addEventListener('load',rollClouds,false):
window.attachEvent('onload',rollClouds);
But i've noticed that, with time my PC CPU memory usage increased ! causing overload on my pc and if i disabled that javascript code, it back to normal.
My question
so i think i need to modify this javascript code that it not keep working forever, i mean, i want to make it to repeat that action only 5 times then stop , maybe i need to define value of g but i'm not good in javascript so any help ~ Thanks.
You need to use a variable to count how many times that function was executed, and use setInterval instead of setTimeout: See example
http://jsfiddle.net/EQDjx/206/ (my counter start from 100 and goes down to 0)
for a more nice effect i recomand you to use jquery. See animate function
http://api.jquery.com/animate/
var g = 1000;
var speed=300;
var counter = 100;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
if (counter < 1) clearInterval(interval);
}
interval = setInterval(function(){rollClouds()}, speed)
A cleaner solution might be to use jQuery to move the background:
function moveClouds() {
$("#clouds_image").css({left:"-2000px"});
$("#clouds_image").animate({left:"2000px"},10000);
}
Then you might set an interval to trigger it every x milliseconds.
setInterval(moveClouds,10000)
JSFiddle is here: http://jsfiddle.net/qXpVX/

Categories