Increase value / Script - javascript

I need some help with increases value / 1 per second.
I have
<script>
function incrementValue()
{
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
return false;
}
</script>
Now I need a function that will increase the value of 'number' and start adding +1 every second until I click on another image.
The only thing I am capable of making is:
function incrementvale()
var incrementTime = 1;
var incrementBy = 1;
private var counter = 0;
function Start () {
InvokeRepeating("Increment", incrementTime, incrementTime);
}
function Increment () {
counter += incrementBy;
}
Which is horribly wrong!
Question!
When I click on image.
Function starts.
The function increases the value of 'number' by 1 every second.
Thanks

If you really want to increase a value exactly after 1 second I would suggest you save the start time (Unix time stamp e.g. seconds since 1/1/1970). And if you want to know the value of your increasing variable just subtract from start value.
Because you mentioned PHP and showed us JS Code I keep it in Pseudo-Code
function getUnixTimeStampNow() {
return Math.round((new Date()).getTime() / 1000);
}
var start = getUnixTimeStampNow();
// at any time do
var current_value = getUnixTimeStampNow() - start;

Related

Changing a variable value/re referencing it with SetIncrement

I have a timer I use to count how many masks are made in a production environment. I use a variable value that is user input when the page is started - it is called SAMS, basically how many masks 1 person can make in an hour would be what I would input depending on how many people I have working. IE. 2 people may be 18, 1 may be 9 etc. The problem I have with my current build is that I cannot change the SAMS value if I have someone leave for the day. So then what I use that value to calculate is off (I use it to show a GOAL value that increments based on the value).
Here is the relevant code for the processes I've described.
var SAMSINPUT = input;
console.log(SAMSINPUT);
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
var output2 = document.getElementById('output2');
setInterval(function doIncrement() {
if (clear == false) {
goal += 1;
output2.innerHTML = goal.toString();
}
}, SAMSINPUT * 1000);
I also have START/STOP/RESET buttons on the page for the timer itself. I tried putting the SAMSINPUT input into the stop button, because if I could stop it, put in a new SAMSINPUT - and have the increment adjusted to the new value, that would solve this for me. However, that doesn't seem to change the actual value that SetInterval references, if I start with a 5, then change it to a 10 that way, it still increments at 5.
Would this work? Let me know if you have any problems/issues.
var SAMSINPUT = 1;
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
var output2 = document.getElementById('output2');
function doIncrement() {
goal += 1;
output2.innerHTML = goal.toString();
}
var inter = setInterval(doIncrement, SAMSINPUT * 1000);
function changeAmount() {
var newVal = document.getElementById('newval').value
clearInterval(inter);
var a = setInterval(doIncrement, newVal * 1000);
}
<div id='output'>
</div>
<div id='output2'>
</div>
<input type="number" id="newval">
<button onclick='changeAmount()'>new SAMSINPUT</button>

Increment Bitcoin Numerif Format Javascript

Hello why i try to coding something like a counter for bitcoin. this is the Code
result: <div id="counter"></div>
This is the Html
This is Javascript Code
var INTERVAL = 1; // in seconds
var INCREMENT = (0.00000001).toFixed(8); // increase per tick
var START_VALUE = (0.00000001).toFixed(8); // initial value when it's the start date
var count = 0;
$(document).ready(function() {
var msInterval = INTERVAL * 3000;
count = INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = count;
window.setInterval( function(){
count += INCREMENT;
document.getElementById('counter').innerHTML = count;
}, msInterval);
});
Heres the Output you can check
https://jsfiddle.net/8eqc2b3t/
Can anyone help
First of all, I've modified your code a little to make a bit more sense, you're using a few keywords that could be reserved within certain languages, so I'd avoid that in future ( like using count as a variable name )
var interval = 1; // in seconds
var increasePerTick = (0.00000001).toFixed(8); // increase per tick
var startingValue = (0.00000001).toFixed(8); // initial value
var $counter = $('#counter');
var btcAmount = 0.00000000;
$(document).ready(function() {
var msInterval = interval * 1000; // Convert to Milliseconds
$counter.text(startingValue); // Set initial amount
window.setInterval( function(){
btcAmount = (parseFloat(btcAmount)+parseFloat(increasePerTick)).toFixed(8);
$counter.text(btcAmount);
}, msInterval);
});
The main issue was that when you were using the + operand you were adding to the string rather than adding the two floats together. You'd also not added jQuery to your Fiddle, causing it not to work, I've fixed this and shown how to do the calculation here too, which basically is to parse both the floats, set them toFixed(8) and then print them to the counter.
The addition part is here:
btcAmount = (parseFloat(btcAmount)+parseFloat(increasePerTick)).toFixed(8);
You were also converting your msInterval incorrectly. Now seconds in interval should work out correctly when changed.
Hope this helps.
Edit:
Forgot to add the Fiddle, sorry! : https://jsfiddle.net/20Lppogq/

function to calculate function fps

Ok so I believe I could best describe the issue through code so here goes
var clicks = 0;
//function to calculate
function clicking(){
clicks += 1;
}
//function to calculate fps where fn is the name of the function
function FPS(fn){
//do stuff
}
Okay so to clarify I dont want to add a variable to the actual function clicking I would like to be able to call something like
FPS(clicking) and have the function return a value for example
var fps = FPS(clicking);
then i could display the returned number as such
element.innerHTML = fps
EDIT:
I know with the current code it seems silly but this is just example coding not what I am actually using
This is not very actual since Date.now() also uses time.
function FPS(fn) {
var startTime = Date.now();
fn();
var endTime = Date.now();
return endTime - startTime;
}
function longClick() {
var abc = 0;
for (var i = 0; i < 100000000; i++) {
abc++;
}
}
var fps = FPS(longClick);
console.log((fps / 1000) + ' seconds');
FPS usually refers to Frames Per Second which is the frequency of refreshing screen image.
Pick a more comprehensive name, with keywords like Elapsed, for teammates.
If you want to know "how fast the functions runs" :
/**
* Return the execution time of a function
* #param {Function} fn The function to execute
*/
function FPS(fn) {
var start = new Date().getTime();
fn();
var end = new Date().getTime();
return end - start;
}
You can have FPS return a DOMHighResTimeStamp (works in IE 10+, Firefox 15+, Chrome 20+, Safari 8+) which will return time in milliseconds. If you want it to work in older browser you can replace the precision timing with a Date (new Date()) object but the Date object will only nab you time in seconds (not milliseconds):
var clicks = 0;
//function to calculate
function clicking(){
clicks += 1;
}
//function to calculate fps where fn is the name of the function
function FPS(fn){
var start = performance.now();
fn();
return performance.now() - start;
}
console.log("Function took " + FPS(clicking) + " milliseconds!");
Here is some pseudo code to get what I think you're looking for - assuming you have a game loop and you're calling FPS in your game loop. As I said - more details about the specifics (such as components) of your game would be helpful.
var clicks = 0;
var fps = 0;
var elapsedTime;
//function to calculate
function clicking(){
clicks += 1;
}
//function to calculate fps where fn is the name of the function
function FPS(fn){
// Get start time
//call fn
// Get stop time
// var delta = stop time - start time
// elapsedTime += delta;
// fps++;
// If elapsedTime > 1 second
// then while elapsedTime > 1 second... elapsedTime -= 1 second and fps = 0;
// We use the while loop here in the event that it took more than 1 second in the call
// But you could just reset elapsedTime back to 0
}
This FPS(fn) would be called anywhere in your game in place of the original function to see how many times that function is called a second.
To answer the original question:
Okay so to clarify I dont want to add a variable to the actual function clicking I would like to be able to call something like FPS(clicking) and have the function return a value for example
Firstly you need to return a value from your clicking function, or any function you plan to pass to the FPS method.
var clicks = 0;
//function to calculate
function clicking(){
clicks += 1;
return clicks;
}
Then in your FPS function, you need to return that value as well.
//function to calculate fps where fn is the name of the function
function FPS(fn){
//do stuff
return fn();
}

Javascript decimal increment?

I've got the following variable JS:
http://jsfiddle.net/c8u8wLsL/13/
$(document).ready(function () {
var total = 15.5,
value = 0,
elem = $('div');
var interval = setInterval(function () {
elem.text(value.toFixed(1) + '$');
if (value >= total) {
clearInterval(interval);
}
value = value + 0.1;
}, 5);
});
Two questions:
The resulting number is 15.6 why?
How can I make the incrementation spend the same amount of time from 0 to the target value? (from 0 to 25 spends the same time as from 0 to 250)
You forget to exit from function. Also you should probably update node's text after checking total.
if (value >= total) {
return clearInterval(interval);
}
elem.text(value.toFixed(1) + '$');
fiddle http://jsfiddle.net/Lqxsh39q/
To solve second problem you can pre-calculate duration of each interval before it setup. And use it like second argument in setInterval. Something like duration = 1000 / (total * 10); or any formula that you want.
fiddle: http://jsfiddle.net/Lqxsh39q/1/
#Glen Swift's answer is correct but I have to point out regarding your original code:
You get the resulting number as 15.6 because:
When you think you are getting 15.5 as the result, you are actually getting 15.4999999, which is smaller than 15.5 and hence the if condition is false even if you think it is true. So it gets incremented once again, giving the final result as 15.6.
As far as the second part is concerned, to get the same time, you need to have the same number of steps for each addition rather than the fixed 0.1. Let's say you want to reach the target in 100 steps everytime, you can divide the total interval by 100 and then replace it in the code where you are writing 0.1 currently.
The final code should look something like:
$(document).ready(function () {
var total = 15.5,
value = 0,
ment=(total-value)/100,
elem = $('div');
var interval = setInterval(function () {
if (value >= total) {
return clearInterval(interval);
}
elem.text(value.toFixed(1) + '$');
value = value + ment;
}, 5);
});
See the fiddle here
Your existing code:
var interval = setInterval(function () {
elem.text(value.toFixed(1) + '$');
if (value >= total) {
clearInterval(interval);
}
value = value + 0.1;
}, 5);
It should check for the >= total condition first. if condition fails then exit the function.
But you are modifying the text element before the check. thus your error.
This would do.
var interval = setInterval(function () {
value = value + 0.1;
if (value <= total) {
elem.text(value.toFixed(1) + '$');
} else {
clearInterval(interval);
}
}, 5);

Incrementing a number smoothly with a variable time period in JS

I have a really simple JS counter which I display on a dashboard like screen which does the following:
Every 5 minutes it makes an jsonp call and retrieves a "total" number
It then displays this number to the screen by incrementing the last total displayed till it is equal to the new total. (the number can only ever increase)
I'm having some trouble with making the number increment smoothly. What I would like to do is find a delta (i.e. New total - old total) and increment the number gradually over the 5 minutes till the next call so it looks like a nice smooth transition.
Any ideas on how I can do this?
Currently some of my code looks like this (This block get's called every 5mins. And yes, it's in dire need of a refactor...)
var LAST_NUMBER_OF_SESSIONS = null;
var five_minutes_in_seconds = 300;
var new_number_of_sessions;
$.getJSON('http://blah.com/live_stats/default_jsonp.aspx?callback=?', function(data) {
if(LAST_NUMBER_OF_SESSIONS === null){
LAST_NUMBER_OF_SESSIONS = data.total_sessions;
}
new_number_of_sessions = data.total_sessions;
var delta = Math.floor(new_number_of_sessions - LAST_NUMBER_OF_SESSIONS);
var time_interval = (five_minutes_in_seconds / delta) * 1000;
var old_value = LAST_NUMBER_OF_SESSIONS;
var new_value = null;
sessions_interval = setInterval(function (){
new_value = parseInt(old_value, 10) + 1;
$('#stats').text(new_value);
old_value = new_value;
if(new_value >= new_number_of_sessions){
clearInterval(sessions_interval);
}
}, time_interval);
LAST_NUMBER_OF_SESSIONS = new_value;
});
}
This code it seems to increment the number very quickly at the start of the 5min period and then stop so it's not exactly right...
Try this:
var total = 0,
delta = 0,
stats = $('#stats').text( total );
function increment() {
var v = +stats.text();
if ( v < total ) {
stats.text( v + 1 );
} else {
$.getJSON('http://...', function(data) { // added data here
delta = Math.floor( 300000 / ( data.total_sessions - total ) );
total = data.total_sessions;
});
}
setTimeout(increment, delta);
}
Update:
In order to test my code, I had to simulate the JSON reponse - I used an array of numbers. See here: http://jsfiddle.net/simevidas/MwQKM/
(In the demo, I use an interval of 5 seconds instead of 5 minutes.)
I am not exactly sure why your code doesn't work as expected, although I suspect that it has to do with line LAST_NUMBER_OF_SESSIONS = new_value;. I wrote something similar and it works fine. It's not that different from what you have, minus that last line of code.

Categories

Resources