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.
Related
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>
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>
i started js a few days ago and made a slider that changes the images when the button is clicked and a timer that changes images automatically every 5 sec. But when i clicked the buttons the timer didnt reset. I used clearInterval to stop the timer but i dont know how to call it to restart it. Here is my Js code.
//progression bar
var width = 1;
//the images
const images = [
"https://www.travelercar.com/wp-content/uploads/2016/04/4a36e314016aa914f203ea6b7d579dc6_large.jpeg",
"https://lemag.nikonclub.fr/wp-content/uploads/2017/07/08.jpg",
"https://www.yourvalleynews.co.uk/wp-content/uploads/2018/03/pic-outside-1080x675.jpg",
];
//the buttons
const suivant = document.getElementById('button1');
const precedent = document.getElementById('button2');
//change image every 5 sec
var counter = 0;
var imageChange;
imageChange = setInterval (function () {
if (counter >= 2 ){
counter -= 2;
document.getElementById("currentImage").src = images[counter];
}
else if (images[0]){
document.getElementById("currentImage").src = images[++counter];
};
}, 5000);
//make buttons work
precedent.onclick = function() {
width = 0;
clearInterval(imageChange);
//I know i have to put something on this line with v imageChange but i dont know what
if (counter <= 0){
counter += 2;
document.getElementById("currentImage").src = images[counter];
}
else{
document.getElementById("currentImage").src = images[--counter];
};
}
suivant.onclick = function() {
width = 0;
clearInterval(imageChange);
//I know i have to put something on this line with imageChange but i dont know what
if (counter >= 2 ){
counter -= 2;
document.getElementById("currentImage").src = images[counter];
}
else{
document.getElementById("currentImage").src = images[++counter];
};
}
//progression bar
function progression(){
var progres = document.getElementById('progression');
var temps = setInterval(frame, 50);
function frame() {
if (width >= 100){
width = 0;
}
else{
width++;
progres.style.width = width + '%';
}
}
}
window.onload = progression;
Feel free to say if have to change some of my ways in the code to make it cleaner. And thanks for taking to help me :)
The main thing is that you have to call setInterval again after you click, in order to restart the interval. Calling clearInterval stops the interval from running.
Here's a way to clean this up a bit:
let counter = 0;
let intervalId;
const getNextImage = (direction) => {
const increment = direction === 'forward' ? 1 : -1;
counter += increment;
if (counter > images.length - 1) {
counter = 0;
}
if (counter < 0) {
counter = images.length - 1;
}
document.getElementById("currentImage").src = images[counter];
};
const startImageLoop = (direction) => {
width = 0;
clearInterval(intervalId);
getNextImage(direction);
intervalId = setInterval(() => {
getNextImage(direction);
}, 5000);
}
precedent.onClick = () => startImageLoop('backward');
suivant.onClick = () => startImageLoop('forward');
Example
var text = 'ENTER...';
var chars = text.split('');
var enter = document.getElementById("enter")
var i = 0;
setInterval (function(){
if (i < chars.length){
enter.innerHTML += chars[i++];
}else{
i = 0;
enter.innerHTML = "";
}
}, 200);
I'm trying to have this typing "enter" effect and I am wondering how to make it only go once. So it will type out "ENTER..." and then stop.
Example
var text = 'ENTER...';
var enter = document.getElementById("enter")
var i = 0;
(function nextLetter() {
enter.innerHTML = text.substr(0, ++i);
if (i < text.length) {
setTimeout(nextLetter, 200);
}
})();
edit: you either have to use setTimeout (one time "sleep"), or remember return value of setInterval and destroy that timer by clearInterval after you don't need it/want it running.
If you use interval, you have to stop the it with clearInterval. Stop it inside the interval function, which is declared as a variable, in the if-statement:
var text = 'ENTER...';
var enter = document.getElementById("enter")
var i = 0;
var interval = setInterval(function() {
enter.innerHTML += text[i];
i += 1;
if(i === text.length) {
clearInterval(interval);
}
}, 200);
JSFiddle
var text = 'ENTER...';
var chars = text.split('');
var enter = document.getElementById("enter")
var i = 0;
var interval = setInterval (function(){
if(i == chars.length) {
clearInterval(interval);
return;
}
if (i < chars.length){
enter.innerHTML += chars[i++];
}else{
i = 0;
enter.innerHTML = "";
}
}, 200);
<div id="enter"></div>
I am currently writing a code to create a slideshow. My pause button works one time around but once it starts playing again and then doesn't pause again. & same thing once i press the increase button. decrease button doesn't work. I have tried anything. Can someone point me in the right direction or let me know what is wrong. http://jsfiddle.net/#&togetherjs=7F7KQf0TtS
var pic= new Array();
var pcount= 0;
var pindex = 0;
var ptimer;
var cap= new Array();
var ccount= 0;
var cindex = 0;
var ctimer;
var resetButton = document.getElementbyId('resetButton');
resetButton.onclick= reloadPage;
function getallpics(){
var size = prompt("How many pictures are you uploading?");
for (var i = 0; i<size; i++) {
pic[i] = prompt("Enter picture filename:");
pindex++;
cap[i] = prompt("Enter caption:");
cindex++;
}
}
function getpics() {
pcount++;
if (pcount > pindex) {
pcount = 1;
}
document.getElementById("pictures").innerHTML= "<img src=" +pic[pcount-1]+ ">";
}
function getcaps(){
ccount++;
if(ccount > cindex){
ccount=1;
}
document.getElementById("captions").innerHTML = cap[ccount-1];
}
function displaypics() {
ptimer = setInterval("getpics()", 3000);
ctimer = setInterval("getcaps()", 3000);
}
function pause(){
clearTimeout(ptimer);
clearTimeout(ctimer);
}
function increase() {
ptimer = setInterval("getpics()", 1000);
ctimer = setInterval("getcaps()", 1000);
}
function decrease() {
ptimer = setInterval("getpics()", 6000);
ctimer = setInterval("getcaps()", 6000);
}
function reloadPage(){
window.location.reload();
}