JS < (less than) Operator Failing - javascript

I have a script that AJAXes a request every 10 seconds (but technically 11), for the user. I have a simple countdown made from 10 to 0 and then again and again.
This countit function is called after each AJAX request to restart
Here is my code:
function countit() {
var count = 10;
loading = setInterval(function() {
$(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
count--;
if (count <= 0) {
clearInterval(loading);
}
}, 1000);
}
The code works fine except, if you leave the page and come back, the countdown proceeds into negative and does not stop. Here is the image:
I cant be sure if this is a problem with the code or JS but the counter doesnt go below 0 when the user stays on the page.

As Ibrahim & Chris have said:
Add a var infront of the Interval as without it, the variable is global.
function countit() {
var count = 10;
var loading = setInterval(function() {
$(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
count--;
if (count <= 0) {
clearInterval(loading);
}
}, 1000);
}

Related

How to create a simple countdown timer in JS?

I have very little experience in coding in general, however, I still need a timer that comes on a pop-up that goes from 20 or 30 minutes to 0, and it should display the time remaining (like MM:SS). Then, when the timer hits 0, a new pop-up should appear that displays some plain text. Is this even possible?
This could do the work
let time = 5;
let element = document.getElementById('countdown');
function lower() {
if(time >= 0) {
element.innerHTML = time--;
}
else {
console.log('popup')
//open popup here
}
}
setInterval(lower, 1000);
I did not do the time format tho. Only shows in seconds now

if/else and setInterval

<script>
//when user clicks start button this function ensures all fields //are set to 0 and it
//sets the timer for the game (90seconds) and the second timer to //call showWord() every four seconds to display a new word
function startGame() {
numBadWordsField.innerHTML = '';
numGoodWordsField.innerHTML = '';
numWordsRight = 0;
numWordsWrong = 0;
correctWords = [];
showWord();
gameTimer = setInterval(gameTime, 1000);
timedWordDisplay = setInterval(showWord, 4000);
}
//this function is set to repeat every four seconds unless the user //types the word
//correctly in which case code in the checkWord() function resets setInterval then and a new word appears
function showWord() {
let randomNum = Math.floor(Math.random()*wordsLevelOne.length);
currentWord = wordsLevelOne[randomNum];
//i put all correctly typed words in an array to avoid them being repeated
//if the random word has been typed correctly and is in the array then i tell the
//program to repeat the function until a new word is found.
if (correctWords.includes(currentWord)) {
showWord();
} else {
wordDisplayBox.innerHTML = currentWord;
setInterval(changeBar, 500);
answerBox.focus();
}
}
//this function is called oninput as user types in the word. it works perfectly (i think it does anyways)
//however i cannot figure out how to give instructions in the event the user does not type the
//word correctly before the four seconds are up and the setInterval repeats. I would like to
//in that case increment the words wrong score and reset the fields to be ready for the next
//word to be displayed
function checkWord() {
let currentWordLen = answerBox.value.length;
if (wordDisplayBox.innerHTML === answerBox.value) {
clearInterval(timedWordDisplay);
numWordsRight++;
correctWords.push(currentWord);
numGoodWordsField.innerHTML = numWordsRight;
answerBox.value = '';
answerBox.focus();
wordDisplayBox.innerHTML = '';
showWord();
timedWordDisplay = setInterval(showWord, 4000);
} else if (answerBox.value === currentWord.substring(0, currentWordLen)) {
answerBox.style.borderColor = 'green';
} else {
answerBox.style.borderColor = 'red';
}
}
//different topic than above but i also researched how to make my progress bar fill slowly over the course
//of the four seconds. i have written the following function identically to that on
//w3schools and other code yet it does not work.
//Any ideas?
function changeBar() {
let proBar = document.querySelector('#progressBar');
var width = 1;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
proBar.style.width = width + '%';
}
}
}
</script>
This project Im working on is a beginner level speed typing game that displays a different word for the user to type in less than four seconds.I have a setInterval that displays a different word every four seconds unless the user types the word correctly at which point the timer starts over then. What I am stumped at is how can I make it so that if the correct answer is not typed in before the interval resets (at the end of four seconds) the program knows to increment the 'wrong answer' score and to reset the input boxes for the next word just like when it is typed correctly. i have attached the parts of my code i think may be relevant. If anyone has any suggestions let me know. I am eager to learn. **I am not familiar yet with JQuery. Please describe any suggestions using vanilla JS
This feature should be implemented in the showWord function.
showWord is executed after 4 seconds have passed, which is when the time is up. Executing this function means the user has failed to type the word in time.
I would do something like this :
function showWord() {
// At this point, the user has lost. We perform the according operations
numWordsWrong++;
answerBox.value = '';
// etc.
// What follows is the rest of the function you've already implemented
let randomNum = Math.floor(Math.random()*wordsLevelOne.length);
// etc.
}
To answer your question about the progress bar, you are setting an interval to run changeBar every 500 milliseconds, which would cause the progress bar to reset every half second. If you want a delay before starting the progress bar use setTimeout.
In addition, you are running your progress bar to move 1% every 10 milliseconds which would result in the bar completing in 1 second. If you want the bar to complete in 4 seconds, set the id interval to run every 40 milliseconds.
Without seeing your css and html, I have to assume you're using the correct id names in your code but if nothing is happening at all, that could also be the cause.
I have looked at the W3Shools code you reference and I tried to replicate what you were trying to do and got this to work:
<html>
<head>
<style>
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
</style>
</head>
<body>
<div id="myProgress">
<div id="myBar"></div>
</div>
</body>
<script>
function changeBar() {
let proBar = document.querySelector('#myBar');
var width = 1;
var id = setInterval(frame, 40);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
proBar.style.width = width + '%';
}
}
}
setTimeout(changeBar, 100);
</script>
</html>
One solution can be to create a new function (ex : showWordBecauseTimeout) and call it in your setInterval instead of showWord. And call that function in showWord fct instead of in startGame fct.
So the new code would be something like :
function showWord() {
clearInterval(timedWordDisplay);
timedWordDisplay = setInterval(showWordBecauseTimeout, 4000);
// you also need to move the cleaning of the input in the showWord fct
// ...
}
function showWordBecauseTimeout() {
numWordsWrong++;
showWord()
}
Hope that it helps you :).

Rails timer countdown, which doesn't reset after page refreshing

I'm creating Rails web application. I want create timer for 15 seconds, which does not reset when I refresh page. I've tried use jQuery countdown from Keith Wood but when I refresh page, timer resets. So, I think I need create timer on backend but I can't imagine how realize this. Can anyone help? There is my timer code below
$('#timer_' + auct_id).countdown({until: +15, onTick: function(periods) {
var seconds_addition;
if (periods[6] < 10)
seconds_addition = '0';
else
seconds_addition = '';
$('#timer_' + auct_id).text('0' + periods[5] + ':' +
seconds_addition + periods[6]);
}});

Track total time taken for a task

I am building a site where task is assigned to each user and he/she needs to complete the task within a fixed duration of time.
For this is need to track Time taken on each task. I also need to track if the user is sitting idle on the site.
Right now i can do this using this code :
HTML
<a class="btn btn-success btn-lg" id="startTracking" role="button">Start Tracking</a>
<a class="btn btn-danger btn-lg" id="endTracking" role="button">Stop Tracking</a>
<h2 id="testingSince"></h2>
JAVASCRIPT
<script type="text/JavaScript">
var totalSeconds = 0;
var idleSeconds = 0;
$(document).ready(function () {
$('body').on('click','#startTracking',function(){
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 1000); // 1 second
});
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleSeconds = 0;
});
$(this).keypress(function (e) {
idleSeconds = 0;
});
});
function timerIncrement() {
totalSeconds += 1;
idleSeconds += 1 ;
if (idleSeconds > 600) { // 20 minutes
alert('You have been sitting Idle for 10 Minutes');
}
$('#testingSince').text(timeStringfromSeconds(totalSeconds));
}
function timeStringfromSeconds(totalSeconds){
var hours = Math.floor(totalSeconds / 36e2),
mins = Math.floor((totalSeconds % 36e2) / 60),
secs = Math.floor((totalSeconds % 60));
return ("0" + hours).slice(-2)+':'+("0" + mins).slice(-2)+':'+("0" + secs).slice(-2);
}
</script>
So this code works great and the user can see the time spent since he clicked the button. It also tracks user idle time and gives an alert after 10 minutes.
However the only Problem here is that when the page reloads the counter starts from 0. i.e the 2 lines :
var totalSeconds = 0;
var idleSeconds = 0;
I just want the timer counter not to restart and continue from its previous value.
One way of doing this is using Cookies. So i have to update them every second but i am not sure if this is a good Idea.
Please let me know if there is any other way or i need to use browser cookies ?
Many users will not permit cookies on their computers. You should never rely only on cookies. Maybe you should make some script that you can ajax call every second or two or five and store elapsed time in session.

I want to animate 0 counting up to 100

I have made a 10 slide presentation and I'm pretty happy with it but it looks a little stale, I want to add some animations and nice effects in there.
I currently have some text that reads '100%' i would like the page upon load to be at zero and then quickly count up to 100.
How would I do this?
$(document).ready(function(){
var count = 0;
var counting = setInterval(function(){
if(count < 101) {
$('.text').text(count + '%');
count++
} else {
clearInterval(counting)
}
}, 10);
});

Categories

Resources