How to stop javascript counter at specific number - javascript

I have this javascript code for tampermonkey that works on Amazon. What it does is just counts up your gift card balance and makes it look like I am getting money. I want to know if it is possible to make it stop at a specific number.
var oof = document.getElementById("gc-ui-balance-gc-balance-value");
var lastCount = localStorage.getItem("lastCount");
oof.innerText = '$' + lastCount || "$10000";
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(localStorage.getItem("lastCount")) || 10000;
setInterval(function () {
var nextCount = current++;
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}, 0.1);
}
animateValue('gc-ui-balance-gc-balance-value')

Use clearInterval inside your setInterval callback so each time the callback is called, you can check if the new count has reached your threshold and clear the timer if it does.
If you check the value outside of the callback, the logic won't be called at each count increment.
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(localStorage.getItem("lastCount")) || 10000;
var interval = null;
var maxCount = 1000;
var callback = function() {
var nextCount = current++;
if (nextCount === maxCount) {
clearInterval(interval);
}
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}
interval = setInterval(callback, 0.1);
}
Here is a demo:
let current = 0;
let interval = null;
const callback = () => {
let nextCount = current++;
console.log(nextCount);
if (nextCount === 5) {
clearInterval(interval);
}
}
interval = setInterval(callback, 100);

May be by clearing the interval when current reaches to a specific value like this
function animateValue(id) {
// rest of the code
let interval = setInterval(function() {
var nextCount = current++;
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}, 0.1);
if (current === requiredVal) {
clearInterval(interval)
}
return current;
}

Related

How do I get my timer to stop, when my 10th and last question has been answered?

The goal I am trying to achieve is to get my timer to stop when all the questions of my quiz has been answered. I have 10 total questions. I have been able to get the timer to start. But getting ot to stop on the click of submit on the 10th question is something I can't figure out.
Let me know if you know what I am doing
StackOverflow said my code was too long... I added my code to codepen. I also included my JS on here.
// variables
var score = 0; //set score to 0
var total = 10; //total nmumber of questions
var point = 1; //points per correct answer
var highest = total * point;
//init
console.log('script js loaded')
function init() {
//set correct answers
sessionStorage.setItem('a1', "b");
sessionStorage.setItem('a2', "a");
sessionStorage.setItem('a3', "c");
sessionStorage.setItem('a4', "d");
sessionStorage.setItem('a5', "b");
sessionStorage.setItem('a6', "d");
sessionStorage.setItem('a7', "b");
sessionStorage.setItem('a8', "b");
sessionStorage.setItem('a9', "d");
sessionStorage.setItem('a10', "d");
}
// timer
// var i = 1;
// $("#startButton").click(function (e) {
// setInterval(function () {
// $("#stopWatch").html(i);
// i++;
// }, 1000);
// });
// $("#resetButton").click(function (e) {
// i = 0;
// });
//hide all questions to start
$(document).ready(function() {
$('.questionForm').hide();
//show question 1
$('#question1').show();
$('.questionForm #submit').click(function() {
//get data attribute
current = $(this).parents('form:first').data('question');
next = $(this).parents('form:first').data('question') + 1;
//hide all questions
$('.questionForm').hide();
//show next question in a cool way
$('#question' + next + '').fadeIn(400);
process('' + current + '');
return false;
});
});
//process answer function
function process(n) {
// get input value
var submitted = $('input[name=question' + n + ']:checked').val();
if (submitted == sessionStorage.getItem('a' + n + '')) {
score++;
}
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3> <button onclick="myScore()">Add Your Name To Scoreboard!</a>')
}
return false;
}
window.yourPoints = function() {
return n;
}
function myScore() {
var person = prompt("Please enter your name", "My First Name");
if (person != null) {
document.getElementById("myScore").innerHTML =
person + " " + score
}
}
// function showTime() {
// var d = new Date();
// document.getElementById("clock").innerHTML = d.toLocaleTimeString();
// }
// setInterval(showTime, 1000);
var x;
var startstop = 0;
window.onload = function startStop() { /* Toggle StartStop */
startstop = startstop + 1;
if (startstop === 1) {
start();
document.getElementById("start").innerHTML = "Stop";
} else if (startstop === 2) {
document.getElementById("start").innerHTML = "Start";
startstop = 0;
stop();
}
}
function start() {
x = setInterval(timer, 10);
} /* Start */
function stop() {
clearInterval(x);
} /* Stop */
var milisec = 0;
var sec = 0; /* holds incrementing value */
var min = 0;
var hour = 0;
/* Contains and outputs returned value of function checkTime */
var miliSecOut = 0;
var secOut = 0;
var minOut = 0;
var hourOut = 0;
/* Output variable End */
function timer() {
/* Main Timer */
miliSecOut = checkTime(milisec);
secOut = checkTime(sec);
minOut = checkTime(min);
hourOut = checkTime(hour);
milisec = ++milisec;
if (milisec === 100) {
milisec = 0;
sec = ++sec;
}
if (sec == 60) {
min = ++min;
sec = 0;
}
if (min == 60) {
min = 0;
hour = ++hour;
}
document.getElementById("milisec").innerHTML = miliSecOut;
document.getElementById("sec").innerHTML = secOut;
document.getElementById("min").innerHTML = minOut;
document.getElementById("hour").innerHTML = hourOut;
}
/* Adds 0 when value is <10 */
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function reset() {
/*Reset*/
milisec = 0;
sec = 0;
min = 0
hour = 0;
document.getElementById("milisec").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("hour").innerHTML = "00";
}
//adding an event listener
window.addEventListener('load', init, false);
https://codepen.io/rob-connolly/pen/xyJgwx
Any help would be appreciated.
its a pretty simple solution just call the stop function in the if condition of n == total
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3>
<button onclick="myScore()">Add Your Name To Scoreboard!</a>')
stop()
}
https://codepen.io/nony14/pen/VwYREgr
Try using clearInterval() to stop the timer.
https://codepen.io/thingevery/pen/dyPrgwz

javascript function delay or set time out not working

i am trying to code the typed jquery functinality in javascript.I am almost there.HEre i need to add a delay after loading the word.like a few secons(lest say 4 sec) after each word loaded. How can i do it. In tried delay and set time out.It is not working for me or i am placing in wrong position. How can i set it.
var count = 0,
count2 = 0,
arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"],
dir = true;
setInterval(function() {
var interval = setInterval(function() {
document.getElementById('p1').innerHTML = arr[count].substring(0, count2);
if (dir) {
count2++;
if (count2 >= arr[count].length) {
dir = false;
}
} else {
count2--;
if (count2 < 0) {
dir = true;
clearInterval(interval);
}
}
}, 100);
count++;
if (count == 6) count = 0;
}, 2500);
<div style="width=100%">
<span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span>
</div>
Your implementation will have problems if you add “A very long string” in to the array.
I’ve modified your code, hope it will help.
var count = 0,
count2 = 0,
arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"],
dir = true;
var p1 = document.getElementById("p1");
// Turning the intervals to on or off.
var onOff = function(bool, func, time) {
if (bool === true) {
interval = setInterval(func, time);
} else {
clearInterval(interval);
}
};
var eraseCharacters = function() {
// How long we want to wait before typing.
var wait = 1000;
// How fast we want to erase.
var erasingSpeed = 100;
var erase = function() {
p1.innerHTML = arr[count].substring(0, count2);
count2--;
if (count2 < 0) {
dir = true;
// Stop erasing.
onOff(false);
count++;
if (count === 6) {
count = 0;
}
// Start typing.
setTimeout(startTyping, wait);
}
};
// Start erasing.
onOff(true, erase, erasingSpeed);
};
var startTyping = function() {
// How long we want to wait before erasing.
var wait = 4000;
// How fast we want to type.
var typingSpeed = 100;
var type = function() {
p1.innerHTML = arr[count].substring(0, count2);
if (dir) {
count2++;
if (count2 > arr[count].length) {
dir = false;
// Stop typing.
onOff(false);
// Start erasing.
setTimeout(eraseCharacters, wait);
}
}
};
// Start typing.
onOff(true, type, typingSpeed);
};
// Start typing after 2 seconds.
setTimeout(startTyping, 2000);
<div style="width=100%">
<!-- Maybe it should be class. -->
<span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span>
</div>

Break while loop with timer?

I was wondering is it possible to break a while loop with a timer?
looked on the internet but could not find a solution for it.
while (true) {
alert('hi');
} if (timer < 0) {
timer?
document.write('Time is up!');
break;
}
Thank you.
You should use setTimeout for this.
var timer = 3;
setTimeout(excuteMethod, 1000);
function excuteMethod() {
alert(timer + ' call');
timer--;
if (timer >= 0) setTimeout(excuteMethod, 1000);
}
Demo : http://jsfiddle.net/kishoresahas/9s9z7adt/
I'm not sure if this is the correct approach, but it works,
(function() {
var delay = 30;
var date = new Date();
var timer = date.setTime(date.getTime() + delay);
var count = 0;
function validate() {
var now = new Date();
if (+now > timer)
return false;
else
return true;
}
while (true) {
count++;
console.log(count);
if (!validate()) {
console.log("Time expired");
break;
}
// Fail safe.
if (count > 50000) {
console.log("Count breached")
break;
}
}
})()
You can change control value in timer function and break the loop.
var control = true;
while(control)
{
...
}
setTimeout(function(){
control = false;
}, delay); //delay is miliseconds
Or based on counter
var control = true,
counter = 10;
while(control){
...
}
// you can handle as count down
// count down counter every 1000 miliseconds
// after 10(counter start value) seconds
// change control value to false to break while loop
// and clear interval
var counterInterval = setInterval(function(){
counter--;
if(counter == 0)
{
control = false;
clearInterval(counterInterval);
}
},1000);

Cant a function be implemented into while loop?

function start() {
var work = document.getElementById("work").value;
var rest = document.getElementById("rest").value;
var rounds = document.getElementById("rounds");
var timer = document.getElementById("timer");
function countdown() {
var roundsValue = rounds.value;
while (roundsValue > 0) {
var worktime = setInterval(function () {
timer.value = work + "sec";
work = work - 1;
if (work === 0) {
clearInterval(worktime);
}
}, 1000);
var resttime = setInterval(function(){
timer.value = rest + "sec";
rest = rest-1;
if(rest === 0){
clearInterval(resttime);
}
}, 1000);
roundsValue = roundsValue-1;
}
}
}
I am working on my javascript progress right now and I came here with this problem. I want to repeat the same amount of work time and rest time as rounds are but it doesnt work like this and I cant help myself. For example: 8 rounds of 10 seconds of work and then 5seconds of rest. It maybe doesnt work because function cant be implemented into a WHILE loop.
fiddle: http://jsfiddle.net/shhyq02e/4/
Here is a quick fix, may not be the best way to go about it but will get what to do.
http://jsfiddle.net/sahilbatla/shhyq02e/6/
function start() {
var rounds = document.getElementById("rounds");
var timer = document.getElementById("timer");
var roundsValue = parseInt(rounds.value);
(function countdown() {
var work = document.getElementById("work").value;
var rest = document.getElementById("rest").value;
if (roundsValue > 0) {
var worktime = setInterval(function () {
timer.value = work + "sec(work)";
work = work - 1;
if (work === 0) {
clearInterval(worktime);
var resttime = setInterval(function() {
timer.value = rest + "sec(rest)";
rest = rest - 1;
if (rest === 0) {
clearInterval(resttime);
--roundsValue;
countdown();
}
}, 1000);
}
}, 1000);
}
})();
}

JavaScript countdown timer not starting

I tried using this JavaScript countdown timer on my page but the timer won't start.
What am I doing wrongly?
var CountdownID = null;
var start_msecond = 9;
var start_sec = 120;
window.onload = countDown(start_msecond, start_sec, "timerID");
function countDown(pmsecond, psecond, timerID) {
var msecond = ((pmsecond < 1) ? "" : "") + pmsecond;
var second = ((psecond < 9) ? "0": "") + psecond;
document.getElementById(timerID).innerHTML = second + "." + msecond;
if (pmsecond == 0 && (psecond-1) < 0) { //Recurse timer
clearTimeout(CountdownID);
var command = "countDown("+start_msecond+", "+start_sec+", '"+timerID+"')";
CountdownID = window.setTimeout(command, 100);
alert("Time is Up! Enter your PIN now to subscribe!");
}
else { //Decrease time by one second
--pmsecond;
if (pmsecond == 0) {
pmsecond=start_msecond;
--psecond;
}
if (psecond == 0) {
psecond=start_sec;
}
var command = "countDown("+pmsecond+", "+psecond+", '"+timerID+"')";
CountdownID = window.setTimeout(command, 100);
}
}
<span style="color:red" name="timerID" id="timerID">91.6</span>
here is what you need to do first
window.onload = countDown(start_msecond, start_sec, "timerID");
should be
window.onload = function () {
countDown(start_msecond, start_sec, "timerID");
}
also you should avoid using a string in your setTimeout function:
CountdownID = window.setTimeout(function () {
countDown(pmsecond,psecond,"timerID");
}, 100);
See here http://jsbin.com/ifiyad/2/edit

Categories

Resources