Change label text every two seconds and wait executing following cos [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i need some code to change label text every two seconds for example on page load label text is "100" after two seconds is"200" after two more seconds is "300" and ....
i have an array for this meaning,my code is like this:
<script type="text/javascript">
function func_code() {
var codes = null;
var code_arr = null;
var j = null;
var i = null;
codes = "100000,100004,100007,100009,100012";
code_arr = codes.split(',');
var len = code_arr.length;
for (j = 0; j <= len; j++) {
for (i = code_arr[j]; i <= code_arr[j + 1]; i++) {
setTimeout(function () { change_number(i) }, 2000);
******wait here for 2 seconds*******
}
}
// document.getElementById('counter').innerHTML = 5000000;
}
function change_number(i) {
document.getElementById('counter').innerHTML = i;
}
</script>
<label id="counter">123</label>

I'm not sure that I understood correctly..
Maybe you need something like this?
function func_code() {
var codes = "100000,100004,100007,100009,100012";
var code_arr = codes.split(',');
for (i = 0;i < code_arr.length;i++) {
(function(i){
setTimeout(function(){
change_number(code_arr[i]);
}, 2000*i);
})(i)
}
}
function change_number(i) {
document.getElementById('counter').innerHTML = i;
}
func_code();
<div id="counter"></div>

<script>
setInterval(function () { change_number() }, 2000);
function change_number(){
var elem = document.getElementById('counter');
var val = elem.innerHTML;
elem.innerHTML = parseInt(val)+100;
}
</script>
<label id="counter">100</label>

var x = 100;
var myCounter = setInterval(function(){
console.log(x);
x = x+100;
if(x == 110){
clearInterval(myCounter); //to clear interval
}
}, 2000);

A recursive solution would look something like this:
var len = code_arr.length;
function looper(j,len) {
if (j<=len) {
for (i = code_arr[j]; i <= code_arr[j + 1]; i++) {
setTimeout(function () {
change_number(i);
looper(j+1,len); // call the function again
}, 2000);
} // for
} // if
} // function
looper(0,len);

Related

How to Create a Random Text Generator with Countdown Timer in Javascript?

So, I'm trying to create a random text generator in Javascript using Math.floor and Math.random which I combine with countdown timers using Javascript as well. However, the result after the countdown value has been <= 0 does not appear random text that I have made in the function.
In fact, it appears undefined. How's the solution? The script I created is below.
<button id="btn" style="background-color:red;width:30px;height:30px;"></button>
<script>
var timer = 5;
var id;
function create_random_string(string_length){
var random_string = 'X-';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
for (var i, i=0; i < string_length; i++){
random_string += characters.charAt(Math.floor(Math.random() * characters.length))
}
}
function starButton() {
this.style.display = 'none';
id = setInterval(function () {
timer--;
if (timer <= 0) {
clearInterval(id);
document.getElementById("script").innerHTML = create_random_string(5);
} else {
document.getElementById("script").innerHTML = timer + " seconds to get Code";
} }, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = starButton;
</script>
<div id="script"></div>
You were not returning anything from your function. If you don't return function value how it will get it! Check this now.
var timer = 5;
var id;
function create_random_string(string_length){
debugger;
var random_string = 'X-';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
for (var i, i=0; i < string_length; i++){
random_string += characters.charAt(Math.floor(Math.random() * characters.length))
}
return random_string;
}
function starButton() {
this.style.display = 'none';
id = setInterval(function () {
timer--;
if (timer <= 0) {
clearInterval(id);
document.getElementById("script").innerHTML = create_random_string(5);
} else {
document.getElementById("script").innerHTML = timer + " seconds to get Code";
} }, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = starButton;
<button id="btn" style="background-color:red;width:30px;height:30px;"></button>
<div id="script"></div>

How can I reset my SetInterval when going to next question?

I'm building a quiz and now have the problem when going to the next question that my timer is doing weird.... it jumps for example from 4 to 9 and then to 3 but I want it to go to 10 again and just countdown to 0 and jump to the next question. Could someone explain me this? Or is it better to use SetInterval? It would be appreciated if you could help me out with this!
var currentQuestion = 0;
var currentCount = 0;
var maxCount = 3;
var totalScore = 0;
function displayQuestion() {
var question = allQuestions[currentQuestion].question;
var showQuestion = $(document).find(".question-full");
var showQuestionImage = $(document).find(".questions-img");
var questionImage = allQuestions[currentQuestion].questionImg;
var numAnswers = allQuestions[currentQuestion].responses.length;
var answerList = $(document).find(".answers-buttons");
/// SCORE
var scoreCounter = $(document).find(".scoreCounter");
$(showQuestion).text(question);
$(showQuestionImage).html(questionImage);
$(answerList).find("li").remove();
$(scoreCounter).find("span").remove();
$('.result-container').find("h2").remove();
$('.result-container').find("img").remove();
$('.result-container').find("a").remove();
$('<span>'+ totalScore +'</span>').appendTo(scoreCounter);
var answers;
var score;
for(var i = 0; i < numAnswers; i++) {
answers = allQuestions[currentQuestion].responses[i].text;
score = allQuestions[currentQuestion].responses[i].score;
$('<li><button class="nextButton" data-score="'+ score +'" type="button">'+answers+'</button></li>').appendTo(answerList);
}
nextQuestion();
$(".nextButton").on("click", function () {
var score = $(this).data('score');
IncreaseScore();
currentQuestion++;
totalScore += score;
if (currentQuestion < allQuestions.length) {
displayQuestion();
} else {
$('.after-container').fadeIn('slow');
$('.content').fadeOut('slow');
}
});
}
function nextQuestion() {
var tijd = 10;
var interval = setInterval(function() {
tijd--;
document.getElementById("countdowntimer").textContent = tijd;
if(tijd == 0) {
currentQuestion++;
displayQuestion();
console.log(tijd);
clearInterval(tijd);
}
}, 1000);
}
function IncreaseScore() {
currentCount++;
if (currentCount > maxCount) {
currentCount--;
}
}
Really close! Just your interval is not being cleared, as there is the wrong reference:
function nextQuestion() {
var tijd = 10;
var interval = setInterval(function() {
...
clearInterval(tijd);
...
}, 1000);
}
should be
function nextQuestion() {
var tijd = 10;
var interval = setInterval(function() {
...
clearInterval(interval);
...
}, 1000);
}
Your implementation is all fine, just you would have had all the intervals still running until 0 and updating #countdowntimer with whatever one fired last in the second.

Javascript Not Working When Tab Not Active

So, I have a code here that works perfectly fine when I am viewing it in the active browser tab. But, as soon as I minimize or switch between other tabs of the browser (which is chrome by the way) the code starts giving issues. Here is the code below:
var a = document.getElementById("slidermain");
var b = a.getElementsByTagName("IMG");
var len = b.length;
var noOpac = 0;
var fullOpac = 10;
var imgNumb = 0;
function initFade(count){
imgNumb = imgNumb + count;
if(imgNumb < 0){
imgNumb = len;
}
if(imgNumb > len){
imgNumb = 1;
}
elem = b[imgNumb-1];
startFadeEffect(elem);
}
function startFadeEffect(elem){
var opacSetting = noOpac / 10;
if(noOpac > 10){
opacSetting = 1;
}
elem.style.opacity = opacSetting;
elem.style.display = "block";
noOpac++;
var timer = setTimeout(function() { startFadeEffect(elem); }, 55);
if(opacSetting == 1){
clearTimeout(timer);
elem.style.opacity = 1;
noOpac = 0;
setTimeout(function() { endFadeEffect(elem); }, 2000);
}
}
function endFadeEffect(elem){
var opacSetting = fullOpac / 10;
if(fullOpac < 0){
opacSetting = 0;
}
elem.style.opacity = opacSetting;
fullOpac--;
var timer = setTimeout(function() { endFadeEffect(elem); }, 55);
if(opacSetting == 0){
clearTimeout(timer);
elem.style.opacity = 0;
elem.style.display = "none";
fullOpac = 10;
return false;
}
}
function autoFade(){
var loop = setInterval("initFade(1)", 4000);
}
Please not that I have been looking on this site for the answer, but mostly the ones I have found are JQuery based solutions; however, I am looking for a JavaScript only solution in which I might not have to use the get new date function. Please do not mark my question as duplicate as I have done good research. Thanks!
This is not a problem with your javascript, but with Chrome. Chrome does some weird things with your tabs when they aren't active. Add code to "fix the mess", or account for not the tab being active, to recover after tabbing out and back in.

Remove elements slideshow

I try to remove my links one by one from div id="wrapper". But it doesn't work:
window.onload = function () {
setInterval(function () {
var wrapper = document.getElementById("wrapper");
var my_links = wrapper.getElementsByTagName("a");
var i;
for (i = 0; i < my_links.lenght + 1; i++) {
my_links.splice(0, i);
}
}, 5000);
}
What is the problem? How can i fix my snippet?
Typo here and length + 1 should be length - 1:
for (i=0; i<my_links.lenght+1; i++){
should be:
for (i=0; i<my_links.length-1; i++){
Further more
Look at this question over here to find the remove function you are looking for: Remove element by id
So it will be:
for (i=0; i<my_links.length-1; i++){
my_links[i].remove();
}
Remove function only works with the function of the question I posted.

Scoring a Javascript Quiz Script

Hi I some javascript code written to quiz the user on 5 questions and then in theory output their score. As far as I can tell the questions are being scored, I just can't figure out how to output the response. I am having no issues fetching the correct html elements and displaying them. I believe the issue is in the looping elements of the window.onload function. The code is below,
<script type="text/javascript">
var rand = 0;
var right = 0;
window.onload = function () {
reset();
Rrand();
var rangQ = document.getElementById('area').getElementsByClassName('divide');
correct = document.getElementsByTagName('a'), i = 0;
for (i; i < correct.length; i++) {
if (correct[i].className == 'correct') {
correct[i].onclick = function () {
right++;
reset();
Rrand();
}
}
else if (correct[i].className != 'correct') {
correct[i].onclick = function () {
right--;
reset();
Rrand();
}
}
}
}
function Rrand() {
var rangQ = document.getElementById('area').getElementsByClassName('divide');
rangQ[rand].style.display = '';
rand++;
}
function reset() {
var rangQ = document.getElementById('area').getElementsByClassName('divide');
for (var i = 0; i < rangQ.length; i++) {
rangQ[i].style.display = 'none';
}
}
document.write(right);
</script>
window.onload is not executed immidiately. you are writing output, but variable right is changed after that.
you need to either move line
document.write(right);
into window.onload as last line (or after loop) or figure out other way that will be best for you

Categories