Why does this simple script never end? - javascript

I have a simple JavaScript function, that looks like this:
countDown();
function countDown() {
var count = 10;
document.write(count);
if (count > 0) {
count = count-1;;
setTimeout(countDown, 1000);
}
}
Why does the variable count never change? This function never ends . . .

Because the countDown() function sets the variable count to ten every time it is called. A slight scoping change will make the function behave as you might have intended.
var count = 10;
countDown();
function countDown() {
document.write(count);
if (count > 0) {
count = count-1;;
setTimeout(countDown, 1000);
}
}

Related

How to create a counter that increments by 1 every 1-8 seconds(random)

So I think I'm close, but what I've written begins to increment by larger values, and at an increasing speed the longer it runs. I assume this is an issue with the interval not being properly cleared. Please assist in anyway possible.
<html>
<head>
<script type="text/javascript">
function setTimer(){
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
clearInterval(interval);
var interval = setInterval(updateCounter, timer);
}
function updateCounter(){
var counter = document.getElementById("counter");
var count = parseInt(counter.innerHTML);
count++;
counter.innerHTML = count;
setTimer();
}
</script>
</head>
<body style="margin:5%;" onload="setTimer()">
<div id="counter">1</div>
</body>
</html>
Your interval variable is a local variable to setTimer. clearInterval(interval); won't work, because you are passing undefined (the value of interval). It won't throw an error though because of variable hoisting but the value you pass to clearInterval is undefined for sure.
Fix #1:
Declare interval outside setTimer:
var interval;
function setTimer(){
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
clearInterval(interval);
interval = setInterval(updateCounter, timer); // no redeclaring here
}
Fix #2:
Since you are clearing intervals right before setting them again, you could use setTimeout as it perfectly fit your needs:
function setTimer() {
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
setTimeout(updateCounter, timer); // no clearing is needed this time
}
Note:
Your timer variable will be between 1-6 seconds. You said you wanted it to be 1-8, so use:
var timer = (Math.floor(Math.random() * 8) + 1) * 1000;
I don't think the updateCounter method should know it is called from a timer and be responsible for calling setTimer(). What if you want to call the method to update the counter from somewhere else that is not using a timer. Managing the call to updateCounter should be done by the controlling code IMHO.
Also, using setTimeOut() might be better here as you then don't have to manage the intervals.
function setTimer() {
var timer = (((Math.floor(Math.random() * 6)) + 1) * 1000);
setTimeout(function() {
updateCounter();
setTimer();
}, timer)
}
function updateCounter() {
var counter = document.getElementById("counter");
var count = parseInt(counter.innerHTML);
count++;
counter.innerHTML = count;
}
<body style="margin:5%;" onload="setTimer()">
<div id="counter">1</div>
</body>
I would suggest moving setTimer() outside of updateCounter() otherwise you will be creating new intervals everytime you call updateCounter(). Try
function setTimer(){
var timer = (((Math.floor(Math.random() * 6))+1)*1000);
var interval = setInterval(updateCounter, timer);
}
function updateCounter(){
var counter = document.getElementById("counter");
var count = parseInt(counter.innerHTML);
count++;
counter.innerHTML = count;
}
setTimer();
EDIT: removed clearInterval

Execute php after javascript timer has finished

so I have this timer in javascript, but after it has hit 0 i want some php code to execute. I don't really know where to start :/.
My javascript Timer
var count = 4;
var counter=setInterval(timer, 1000);
function timer()
{
count = count-1;
if (count <= 0)
{
...
}
}
execute php here if count = 0;

Javascript setInterval for sequential numbers

I'm writing some code that looks like this
<script type="text/javascript">
setInterval(function write_numbers(){
var count = 1;
var brk = "<br>"
while (count < 1218){
document.write(count + brk);
count++;
}},1000)
</script>
I need it to display the first number which is one then wait one second then display the next number (2) then wait a second, I need this to carry on till it reaches 1218 then stop.
With the code I've written it just writes all the numbers up, waits a second then repeats all the numbers again.
I'm quite new to coding so i don't know how to fix this.
If someone could tell me how to do it, it would be greatly appreciated.
There are multiple issues in your code, although you are using setInterval(), since you have a while loop inside it, the complete loop will be executed every 1 second.
Instead you need to have the setInterval() callback use an if statement to check whether to print the value or not like
var count = 1;
var interval = setInterval(function write_numbers() {
if (count <= 1218) {
document.body.appendChild(document.createTextNode(count));
document.body.appendChild(document.createElement('br'));
count++;
} else {
clearInterval(interval);
}
}, 1000)
The below script should do the trick for you:
<script>
var count = 1;
var brk = "<br>";
var myVar = setInterval(function(){ myTimer() }, 1000); // This should be a global variable for clearInterval to access it.
function myTimer() {
document.write(count + brk);
count++;
if(count > 1218){
myStopFunction();
}
}
function myStopFunction() {
clearInterval(myVar);
}
</script>
two issues
1) If you are using setInterval then you must clear the interval as well otherwise it will be an infinite loop
2) use if rather than while so that number is printed one by one.
try this
var count = 1;
var interval1= setInterval(function write_numbers(){
var brk = "<br>"
if (count < 1218)
{
document.write(count + brk);
count++;
}
else
{
count = 1;
clearInterval(interval1);
}
},1000);
First, you should define count outside setInterval. Defining inside will reset it every time.
Second, while (count < 1218){} should be a conditional statement. I have considered if(count>= 1218) as termination condition.
Third, when even you use setInterval, remember to use clearInterval as well.
Code
var count = 1;
var interval = setInterval(function write_numbers() {
var brk = "<br>"
document.write(count + brk);
count++;
if (count >= 10) {
window.clearInterval(interval);
}
}, 1000)
Try this code man , only one change from your code.
count variable declare out side of the setInterval function
<script type="text/javascript">
var count = 1;
setInterval(function write_numbers(){
var brk = "<br>"
if (count < 1218)
{
document.write(count + brk);
count++;
}
},1000);
</script>

How to speed up the count down?

I am working on a basic countdown using Javascript where, the countdown starts from 0 and then ends till 24 as thats the idea of the countdown, I want to end it at 24. Here's the code:
var count=0;
var counter=setInterval(timer, 50); //1000 will run it every 1 second
function timer()
{
count=count+1;
if (count >= 24)
{
clearInterval(counter);
//counter ended, do something here
document.getElementById("countdown").innerHTML=24 ;
return;
}
//Do code for showing the number of seconds here
document.getElementById("countdown").innerHTML=count ; // watch for spelling
}
Now the thing is that if you notice this, the countdown happens very fast, this is the intended effect. However the question is this, Is there a way to have a smooth easing type effect, where the countdown starts slowly and then speeds up by the end ? How to achieve that effect ?
Thanks for your response.
EDIT: Here is the fiddle, to see the countdown in action and to gain a deeper insight.
You'll need to use setTimeout instead of setInterval and another variable for setTimeout.
var count=0;
var speed = 1000;
timer();
function timer()
{
count++;
//Do code for showing the number of seconds here
document.getElementById("countdown").innerHTML=count ; // watch for spelling
if (count >= 24)
{
return;
}
speed = speed / 6 * 5; // or whatever
setTimeout(timer, speed);
}
Fiddle: http://jsfiddle.net/4nnms1gz/2/
Use a timeout which runs only once then add extra time and run the timeout again until you reach 24.
var count=0;
var ms = 200;
var step = 5;
var counter=setTimeout(timer, ms); //1000 will run it every 1 second
function timer()
{
count=count+1;
if (count <= 24)
{
//Do code for showing the number of seconds here
document.getElementById("countdown").innerHTML=count ; // watch for spelling
ms = ms - step;
counter = setTimeout(timer, ms);
}
}
Using setTimeout will give you more control on your counter.Here is a working example where you can handle the speed of your counter.It will give you a time increase of 30ms to 70ms to each call to time function
var count=0;
var loop=1000;
var interval;
var text=document.getElementById('countdown');
var range=document.getElementById('range');
var btn=document.getElementById('btn');
var span=document.getElementById('val');
range.addEventListener('change',function(e){
span.innerHTML=range.value+' ms';
});
btn.addEventListener('click',function(e){
timer(parseInt(range.value));
});
function timer(time)
{
console.log(time);
if (count < 24)
{
count=count+1;
text.value=count;
loop-=time;
interval=setTimeout(function(){
timer(time);
},loop);
if(count>=24){
clearTimeout(interval);
return;
}
}
}
<input type='text' id='countdown' value='0'></br>
<input type='range' id='range' max='70' min='30' value='30' >increase by:<span id='val'></span></br>
<input type='button' value='start' id='btn' ></br>

JavaScript simple countdown

I want a simple JavaScript countdown which counts to 5 and then stops. I want to show the current value (1,2,3,4,5)
I tried:
function countdown() {
jAlert('test', i);
i++;
if (i >= 5) {
clearInterval(aktiv);
}
};
var aktiv = setInterval('countdown()', 1000);
var i = 0;
But every time I insert that i in to jAlert it wont work any more. What is wrong there?
var $i = 0;
var $interval = setInterval(function()
{
if (++$i === 5)
clearInterval($interval);
jAlert('test', $i);
},
1000);
function countdown () {
// try to see if passing a string, rather than a number works.
jAlert('test', i + '');
i++;
if (i >= 5) {
clearInterval(aktiv);
}
};
var aktiv = setInterval(countdown, 1000);
var i=0;
Also open the firebug console and tell us what error you are getting when you put the i in jAlert. Or make a jsFiddle if possible.
Try to amend this line:
var aktiv = setInterval('countdown()', 1000);
To this:
var aktiv = setInterval(countdown, 1000);
Because when I tried javascript for the first time, this interval thingy wouldn't work if i had quotes and / or parenthesis after the function name.

Categories

Resources