For Loop Not working with inner html Javascript - javascript

I am writing a code in java script to display a countdown from 10 to 0. Loop is working for alert but when i use document.getElementById the loop doesn't work and it shows 0. Here's My Code
heading is the id of h1
function msg(z)
{
try
{
for(var i=0;i<=10;i++)
{
var seconds=z-i;
document.getElementById("heading").innerHTML="Select T
The Multiples of 2 in"+" "+seconds+" "+"seconds";
}
}
catch(e)
{
document.write(e);
}

Have you use debug tools to verify if the problem is in the loop? You are not waiting any second in each loop iteration, so youll see the end result as it will execute in much less than a second, so youll see 0 (the final iteration)
Take a look at this post Javascript Second Counter as is basically the same as you are trying to do.
Hope this helps

I Changed My function to this and it's working fine.
P.S:- I Have Not added any constraints yet!
function msg(){
function timer()
{
seconds -=1;
document.getElementById("heading").innerHTML="Select The Multiples of 2 in"+" "+seconds+" "+"seconds";
}
var cancel=setInterval(timer,1000);
setTimeout(function(){if(cout<10){alert("Time Over You Lose!");}else{alert("You Have Completed Level 1");}},10000);
}

Related

Why can't i output outside a function, in this scenario where i'm creating a simple counter i'm confused as to why it's working inside and not out?

Why can't I output outside the function here, why does it need to be inside?
counter = 0;
function countJar() {
counter += 1
document.getElementById('demo').innerHTML = counter;
}
// why can't it be here?
Because if it were where you've shown in the question, the value would be 0. The code runs immediately on page load, it doesn't wait for something to call countJar. Where it is now, it doesn't run until countJar is called.
If you mean you can't even see 0 when you try to put it there, that would be because the id="demo" element doesn't exist yet. If that's what you mean, this question's answers apply.

slideshow counter disappears

I have this code that is supposed to generate a counter for a slideshow and then change the picture and the corresponding number color in the counter. However, after the slideshow cycles through twice, the counter changes to display:none and then reappears and disappears every time the slideshow begins its cycle.
//icons for newsreel guide
for(i=0;i<document.getElementsByClassName("news").length;i++){
var count=i+1;
$('#counter').append('<span class="count">'+count+'</span>');
}
//newsreel script
$(".news").hide();
setTimeout (function() {
var wait = $(".news:last").index()*12000+12000;
function newsreel(){
var i=0;
(function showNews(elem){
if(i==document.getElementsByClassName("count").length){
i=0;
}
document.getElementsByClassName("count")[i].style.color="#000";
elem.fadeIn(2000,function(){
elem.delay(8000).fadeOut(2000,function(){
document.getElementsByClassName("count")[i].style.color="#3159a0";
i=i+1;
$(this).next().length && showNews($(this).next());
});
});
})
( $(".news:first"));
setTimeout (arguments.callee, wait);
}/*end newsreel()*/
newsreel();
}, 2000);
At first I thought it was using the deprecated arguments.callee but I changed that and it still happens on cue. Any ideas?
I checked your code, and the problem is in this line :
$(this).next().length && showNews($(this).next())
.next() is getting the next sibling. Your counter is a sibling of .news. To solve your problem, do this:
$(this).next().length && showNews($(this).next('.news'))
That will select the next sibling with the class news.
I suspect it's because your showNews function is never running. I think the JavaScript engine is evaluating
(function showNews(elem){
//...
})
and
( $(".news:first"));
as two different expressions, rather than passing $(".news:first") as a parameter to showNews as you intend. Since ; at the end of a line is optional in JS, the parser will insert one automatically if the result is valid JavaScript. In this case, it defines a function but never calls it, then builds a jQuery sequence but never uses it.
Try removing the carriage return between the two:
(function showNews(elem){
//...
})($(".news:first"));

SetTimeout javascript countdown Timer with delay

hi i am confused with the below code
JSfiddle link
for (var i=6;i>=0;i--)
{
setTimeout((function(i)
{
$("div").delay(4000).html(i);
alert(i); //if commented unable to see the countdown
})
(i),4000);
//alert(1);
}
I am not able to get the count down timer.. whats wrong.. when "alert" is commented unable to see the count down numbers.
Please somebody explain how the above code works.. Post some correct code
.delay() only works for jQuery animation methods, not general jQuery methods such as .html()
All of your timeouts are getting fired at once - there's nothing to space them out.
The net result is that (without an alert) every iteration through the loop runs immediately, leaving the div containing 0 having invisibly (and very briefly) contained the other numbers from the previous iterations.
Try this, instead:
function counter($el, n) {
(function loop() {
$el.html(n);
if (n--) {
setTimeout(loop, 1000);
}
})();
}
counter($('div'), 6);
See http://jsfiddle.net/alnitak/t3AA8/
Do not use alert, because alert will stop everything. Use console.log

Making a total number count appear to increase

Basically I have a class counting system that displays the number of classes and displays them in a span element. Below is the code:
$.get('other.html', function(data) {
$('#total').html($('.doc', data).length);
});
This works perfectly, however I'd like a way to have the numbers increasing one by one since the span element contains 0 when the page loads. Here's an example (the numbers increasing on here).
For this I have tried setTimeout and despite this not working anyway, I released it would simply delay the function and then display the end number. I have heard of periodical or something similar being used but could not find this in the example source code.
I am really sorry for more poor phrasing. If you have no idea what I mean then just ask and I'll try rephrase or find a better example.
The key is the function which increases the number should set a setTimeout to call itself, before termination. This way it will always be called again. If you want the option to stop the incrementing, you can add a global variable, and the function will only set a new timeout when that variable is true.
Example:
var doIncrement = true;
var numberToIncrement = 0;
function increment {
numberToIncrement++;
$('#mySpan').text(numberToIncrement);
if (doIncrement) {
setTimeout(increment, 1000);
}
}
You could use the setInterval function that allows you to run code at some time intervals. clearInterval allows to stop the task.
http://jsfiddle.net/d52Pw/
var $totalEl = $('#total');
$.get('other.html', function(data) {
var len = $('.doc', data).length,
count = 0,
int = setInterval(function () {
if (++count === len) {
//when we reach len, we stop the task
clearInterval(int);
}
$totalEl.html(count);
}, 500); //run every 1/2 sec
});

setInterval with an Array

I'd like to use the setInterval function in jQuery in order to create an alert with the content of one array every 4 seconds. However my alerts show all the values of my array within a short amount of time and it stops for 4 seconds after having displayed all the values.
$.each(['html5', 'EDM', 'Coca Cola', 'creativity'], function(id,value) {
setInterval(function(){
alert(value);
}, 4000);
});
In this case, I'd like to display something like : Alert('html5') - 4 seconds - Alert('EDM') - 4 seconds - Alert('Coca Cola') - 4 seconds - Alert('creativity') - 4 seconds - Alert('html5') - 4 seconds - Alert('EDM') - 4 seconds - ...
Move the setInterval from the loop.
var arr = ['html5', 'EDM', 'Coca Cola', 'creativity'];
var index = 0;
setInterval(function() {
console.log(arr[index++ % arr.length]);
}, 4000);​
Live DEMO
No jQuery needed.
Use a recursive setTimeout
var arr = ['html5', 'EDM', 'Coca Cola', 'creativity'];
var alertLoop = function(i) {
if (arr[i]) {
alert(arr[i]);
setTimeout(function(){alertLoop(i+1);}, 4000);
}
}
alertLoop(0);
Demo: http://jsfiddle.net/B5tJw/
Use of setInterval is discouraged. For an explanation, read here: http://bonsaiden.github.com/JavaScript-Garden/#other.timeouts
To summarise the problem:
setInterval fires the event at a regular interval, regardless of what else is happening on the page.
However, Javascript is not multi-threaded: it can only run one code sequence at a time. If setInterval is triggered while another code sequence is being run, the new code sequence will be blocked until the previous one is finished, and will wait for it.
If this happens repeatedly, you can end up with a large number of events waiting to be run.
You're using alert() to display your messages. alert() causes the code execution sequence to pause until the user responds to the message, but keeps it locked, so that other events cannot run their code. This is a particular problem for setInterval, because it fires new events at the specified time, regardless of whether something else is blocking the script.
The solution is to use setTimeout instead of setInterval.
setTimeout is only triggered once, but it is easy to tell it to trigger itself again inside its own function, so you can get the same effect as setInterval, but with much more control. Your code can wait until after the alert() has been accepted by the user before triggering the next event, which means that you won't get the problem of cascading events that can happen with setInterval.
Hope that helps explain things. The link I mentioned at the beginning is also very helpful.

Categories

Resources