clearInterval() function is not working in JavaScript - javascript

i tried to add a simple random number generater upto 10. When code is excecuted its working fine and generating random numbers. after that i added a condition that when function generate 5 random number function should stop working, So I added clearInterval() function but there is no change in output.
var stop = setInterval(timer, 1000);
var t = 0;
function timer() {
var count = 0;
var X = document.getElementById("timer");
var rnumber = Math.floor(Math.random() * 10);
X.innerHTML = rnumber;
count++;
if (count == 5) {
clearInterval(stop);
}
}
<body>
<div id="timer">0</div>
</body>

You are resetting count to 0 every time. Here's how to do it
function timer() {
if (!this.count) this.count = 0;
var X = document.getElementById("timer");
var rnumber = Math.floor(Math.random() * 10);
X.innerHTML = rnumber;
this.count++;
if (this.count == 5) {
clearInterval(stop);
}
}
var stop = setInterval(timer, 1000);
function timer() {
console.log("running");
if (!this.count) this.count = 0;
var X = document.getElementById("timer");
var rnumber = Math.floor(Math.random() * 10);
X.innerHTML = rnumber;
this.count++;
if (this.count == 5) {
clearInterval(stop);
console.log("stopped");
}
}
<div id="timer">a</div>

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 do I change image of a slider closed in another function?

what I have in here is a simple slider with two images. Is there a way to change the var file of imageSwap() when the counter hits 12?
var number = Math.floor(Math.random() * 2) + 1;
var timer1 = 0;
var timer2 = 0;
function imageSwap(id) {
var img = document.getElementById("app" + id);
img.src = "red.png";
img.classList.add("selected");
var count = document.querySelectorAll(".selected").length;
console.log(count);
if (count == 12) {
// Change var file image of function Change()
}
}
function hide() {
$("#slider").fadeOut(500);
}
function change() {
number++;
if (number > 2) number = 1;
var file = '<img src="tree' + number + '.png" />';
document.getElementById("slider").innerHTML = file;
$("#slider").fadeIn(500);
timer1 = setTimeout("change()", 5000);
timer2 = setTimeout("hide()", 4500);
}
Thanks in advance!

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.

Basic Javascript Countdown

Good day fellow developers. Please entertain what must seem like a very simple question: I have a basic countdown with the intent of counting down to 5 and loops continually.
var countDownDiv = document.getElementById('countDown');
window.setInterval(intervalCountDown, 1000);
function intervalCountDown() {
var counter = 5;
countDownDiv.innerHTML = counter--;
}
The problem is that it's not counting down, for what reason I don't know. Here is a fiddle I've created if that helps.
You redefine your counter every time countDown called.
To prevent this, you should define variable in outer scope.
var countDownDiv = document.getElementById('countDown');
window.setInterval(intervalCountDown, 1000);
var counter = 5;
function intervalCountDown() {
countDownDiv.innerHTML = counter--;
}
<span id="countDown"></span>
You can also create something more reusable:
function countDown(from, time, el) {
el.innerHTML = from;
var i = setInterval(tick, time);
function tick() {
el.innerHTML = --from;
if (from <= 0) clearInterval(i);
}
}
countDown(100, 1000, document.getElementById('c1'));
countDown(10, 5000, document.getElementById('c2'));
<span id="c1"></span><hr/>
<span id="c2"></span>
Just put your var counter outside the function intervalCountDown()
var countDownDiv = document.getElementById('countDown');
window.setInterval(intervalCountDown, 1000);
var counter = 5;
function intervalCountDown() {
countDownDiv.innerHTML = counter--;
}
Initialize your counter outside the function.
var countDownDiv = document.getElementById('countDown');
window.setInterval(intervalCountDown, 1000);
var counter = 5;
function intervalCountDown() {
countDownDiv.innerHTML = counter--;
}
You create a new counter variable each tick. Move counter out of the tick function:
var countDownDiv = document.getElementById('countDown');
var counter = 5;
window.setInterval(intervalCountDown, 1000);
function intervalCountDown() {
countDownDiv.innerHTML = counter--;
}
<div id="countDown"></div>
You are redeclaring the counter variable in every turn. Fix: http://jsfiddle.net/4tpcdtdj/1/
var countDownDiv = document.getElementById('countDown');
var counter = 5;
var countInterval = setInterval(intervalCountDown, 1000);
function intervalCountDown() {
if (counter <= -1) {
clearInterval(countInterval);
return;
}
countDownDiv.textContent = counter--;
}
You redefining counter variable with value 5.
You can use closure as below
var countDownDiv = document.getElementById('countDown');
window.setInterval(intervalCountDown(), 1000);
function intervalCountDown() {
var counter = 5;
return function(){
countDownDiv.innerHTML = counter--;
if(counter==0) // Re-initiate counter
counter = 5;
}
}
Your variable counter declared in Locally so again and again assign the same value counter = 5. That is the problem below display my correction
var bingoDiv = document.getElementById('bingo');
window.setInterval(intervalBingo, 5000);
function intervalBingo() {
var newNum = Math.floor(Math.random() * 75) + 1;
bingoDiv.innerHTML = newNum;
}
// basic countdown
var countDownDiv = document.getElementById('countDown');
window.setInterval(intervalCountDown, 1000);
var counter = 5;
function intervalCountDown() {
if (counter == 0) {
counter =5;
}
countDownDiv.innerHTML = counter--;
}
// number randomizer
var bingoDiv = document.getElementById('bingo');
var counter = 5;
var counter_interval = false;
window.setInterval(intervalBingo, 5000);
function intervalBingo() {
var newNum = Math.floor(Math.random() * 75) + 1;
counter = 5;
bingoDiv.innerHTML = newNum;
clearInterval(counter_interval);
countDownDiv.innerHTML = counter--;
counter_interval = window.setInterval(intervalCountDown, 1000);
}
// basic countdown
var countDownDiv = document.getElementById('countDown');
function intervalCountDown() {
countDownDiv.innerHTML = counter--;
}
<div id="bingo"></div>
<hr>
<div id="countDown"></div>
i thing like this, you can try this.
Try this,
var num = document.getElementById("countDown");//Get value from div.
var counter = 5; //Declaring counter value.
num.innerHTML = counter;//assigning counter value to num variable
function deg(){
counter--;//decrementing counter value.
num.innerHTML = counter;//getting output in div using innerHTML
if(counter <= 0){ //if couter value reaches or goes below 0 then stop
// decrementing of counter value.
window.clearInterval(st);
}
}
var st = window.setInterval(deg,1000);

How can I have a live timer that updates every seconds within a 3 second loop?

I'm using some code like this
window.setInterval(function(){
//Code goes here
}, 3000);
for a 3 seconds loop, and I want to have a timer counting up within that that updates every seconds instead of every 3 seconds, is that possible?
I tried putting this in the loop:
var stmints = 0;
var stseconds = 0;
var stzecsec = 0;
function toAutoStop() {
alert('Your life goes on');
}
var zecsec = 0;
var seconds = 0;
var mints = 0;
var startchron = 0;
function chronometer() {
if(startchron == 1) {
zecsec += 1; // set tenths of a second
if(zecsec > 9) {
zecsec = 0;
seconds += 1;
}
if(seconds > 59) {
seconds = 0;
mints += 1;
}
document.getElementById('showtm').innerHTML = mints+ ' : '+ seconds+ '<sub>'+ zecsec+ '</sub>';
if(zecsec == stzecsec && seconds == stseconds && mints == stmints) toAutoStop();
else setTimeout("chronometer()", 100);
}
}
function startChr() { startchron = 1; chronometer(); } // starts the chronometer
function stopChr() { startchron = 0; } // stops the chronometer
function resetChr() {
zecsec = 0; seconds = 0; mints = 0; startchron = 0;
document.getElementById('showtm').innerHTML = mints+ ' : '+ seconds+ '<sub>'+ zecsec+ '</sub>';
}
startChr();
You may want to make your period 1s then:
var UPDATE_PERIOD = 1;
var ACTION_PERIOD = 3 * UPDATE_PERIOD;
var passed = 0;
setInterval(function() {
passed += UPDATE_PERIOD;
updateTimer();
if(passed % ACTION_PERIOD === 0) {
doStuff();
}
}, UPDATE_PERIOD * 1000);
function updateTimer() {
document.getElementById("timer").textContent = "" + passed + "s";
}
function doStuff() {
// do your stuff here
}
Very simple example: http://jsbin.com/aSAQiYud/1/edit
http://jsfiddle.net/459Lt/
this is actually very easy. I used jquery but that's for just selecting elements. Nothing truly that controls logic.
w.clone().appendTo('body'); is where you would like to put function that needs to be called... like dowork().....
var t=0, w=$('.w'),txt=$('.text');
setInterval(f,1000);
function f(){
txt.text(t+1);
if(t==2) w.clone().appendTo('body');
t=++t%3;
}

Categories