Start/Stop invertal if variable is too high JS [duplicate] - javascript

This question already has answers here:
Stop setInterval call in JavaScript
(7 answers)
Closed 7 years ago.
Is it possible to have a invertal function that stop and starts if a variable is too high or too low
How can I make moneymaker stop when it reach 300?
I Tried with this code, but didn't get any results...
Code ex.
var money = 0;
var maxmoney = 300;
var moneymaker = window.setInterval(function(){
money = money + 1;
document.getElementById('money').innerHTML = money;
}, 1000);
function stopInter(){
if(hp >= maxhp)
clearInterval(regen);
}else{
setTimeout(function(){}, 1000);
}
}

var money = 0;
var maxmoney = 300;
var moneymaker = window.setInterval(function(){
if(maxmoney>money){
money = money + 1;
console.log(money);
}
document.getElementById('money').innerHTML = money;
}, 1000);
https://jsfiddle.net/4L2s5e0y/2/

Related

Why is difference between date() is NaN? [duplicate]

This question already has answers here:
What does var mean in Javascript? [closed]
(2 answers)
Closed 2 years ago.
<script>
var start;
function shapeAppear() {
document.getElementById("shapes").style.display = "block";
var start = new Date().getTime();
}
function delay() {
setTimeout(shapeAppear,Math.random() *2000);
}
delay();
document.getElementById("shapes").onclick = function() {
document.getElementById("shapes").style.display = "none";
var position = Math.floor(Math.random() * 500);
document.getElementById("shapes").style.left = position + "px";
document.getElementById("shapes").style.right = position + "px";
document.getElementById("shapes").style.top = position + "px";
document.getElementById("shapes").style.bottom = position + "px";
var end = new Date().getTime();
var time = end - start;
time /= 1000;
document.getElementById("time").innerHTML = time + "s";
delay();
}
</script>
Here in this code i want the date() function to return a specific integer value.
Because when we subtract the two Date() functions we must get the integer value.
It is a scoping issue. if you use var inside a function, that variable will only exist in the scope of that function.
So what you could do is this:
var start;
function shapeAppear() {
start = new Date().getTime();
}
By removing var in the shapeAppear function, you're updating the var that is created outside the function.
Besides that as Rodney mentioned you call delay before shapeAppear which means that start is not defined when calling delay.
Hope that makes sense.

Objects, prototypal inheritance, and a failing function [duplicate]

This question already has answers here:
How to call a function in Javascript [duplicate]
(4 answers)
Closed 5 years ago.
While trying to move on to some intermediate/advanced Javascript concepts, I've run into a problem. In the following code, the object prototype and created objects seem to be functioning fine. But when I try to then use them in the function 'winner', the result always declares the winner as the second argument passed, regardless of their score. Here, Mike has a higher score(395) than Peter (206) and should be declared the winner. Also, the console is logging the message "Peter wins with a score of function () {
return (this.age * 5) + this.height;
}".
Any help understanding what I'm doing wrong would be greatly appreciated.
var player = {
name: 'Default',
age: 'Default',
height: 'Default',
score: function() {
return (this.age * 5) + this.height;
}
}
var Mike = Object.create(player);
Mike.name = 'Mike';
Mike.age = 67;
Mike.height = 60;
var Peter = Object.create(player);
Peter.name = 'Peter';
Peter.age = 30;
Peter.height = 56;
var winner = function(player1, player2) {
var player1score = player1.score;
var player2score = player2.score;
if(player1score > player2score) {
console.log(player1.name + ' wins with a score of ' + player1.score);
} else {
console.log(player2.name + ' wins with a score of ' + player2.score);
}
}
winner(Mike, Peter);
winner(Peter, Mike);
Replace
var player1score = player1.score;
var player2score = player2.score;
with
var player1score = player1.score();
var player2score = player2.score();
You have to call the function, if you just write player1.score you will get the body of the function.

Make number grow with jQuery using same amount of time for every number

My goal is to perform a jQuery script that'll make any number visually grow from zero until its value with setInterval().
Here's what I came up with:
$('.grow').each(function() {
var $el = $(this);
var max = parseInt($el.text().replace(/\s/g, ''));
var refresh = 5;
var start = 0;
var step = 1;
var interval = window.setInterval(function() {
start += step;
$el.text(start);
if(start >= max)
clearInterval(interval);
}, refresh);
});
My problem is I have numbers ranging from a few hundreds to several hundreds thousands. With this script, bigger number take more time to reach their value.
My goal is to make any number, regardless of its goal value, take the same amount of time to reach it. I sense that I should divide the number by the number of seconds I want the animation to run and then, set the result as the interval step?
I'm inquiring but still seeking for help :)
Thanks.
$('.grow').each(function() {
var $el = $(this);
var max = parseInt($el.text().replace(/\s/g, ''));
var duration = 1000; // shared duration of all elements' animation
var refresh = 5;
var frames = duration / refresh; // number of frames (steps)
var start = 0;
var step = Math.max(Math.round(max / frames), 1); // step should be >= 1
var interval = window.setInterval(function() {
if(start + step < max) {
start += step;
}
else {
start = max;
clearInterval(interval);
}
$el.text(start);
}, refresh);
});
This should work I suppose,
$('.grow').each(function() {
var $el = $(this);
var max = parseInt($el.text().replace(/\s/g, ''));
var start = 0;
var refresh = 5;
var totalSteps = 10;
var step = max/totalSteps;
function calculate(){
start += step;
$el.text(Math.round(start));
if(start < max){
setTimeout(function() {
calculate();
}, refresh);
}
}
calculate();
});
This will always finish in 100 steps. I.e. 100*refresh = 100*5 = 500 seconds.

Javascript - my setTimeOut in a while loop doesn't work [duplicate]

This question already has answers here:
jquery setTimeout or setInterval
(3 answers)
Issues with JavaScript settimeout function
(3 answers)
Closed 10 years ago.
I wanted to do something like this:
<p id="sec">5</p>
<script>
var i = 5;
while (i > 0){
setTimeout(i--,1000);
document.getElementById("sec").innerHTML = i;
}
if (i === 0){
window.location = "index.php";
}
</script>
And without a split second, it redirected me to index.php? Why does this happened? How to make it work?
var i = 5;
setTimeout(updateTime,1000);
function updateTime()
{
document.getElementById("sec").innerHTML = i--;
if (i === 0)
window.location = "index.php";
else
setTimeout(updateTime, 1000);
}

Javascript SetTimeout and Loops [duplicate]

This question already has answers here:
How do I add a delay in a JavaScript loop?
(32 answers)
Closed 9 years ago.
Experts.
Javascript not producing desired delay effect.
From other questions, on SO I got to know that, problem is with settimeout and the way I am using it.
But still I am not able to comprehend, how Settimeout works.
So I am putting code here.
Need to use Javascript only, because of knowledge purpose.
Actually I am trying to clear my concepts about this, closure in javascript.
Are they kind of twisted things of Javascript?
var objImg = new Object();
var h;
var w;
var no = 100;
while (no != 500) {
setTimeout(function () {
size(no, no);
}, 2000);
/* it's get executed once, instead of repeating with while loop
Does it leave loop in mid? I get image with 500px height and
width, but effect is not acheived.
*/
no = no + 50;
}
function size(h, w) {
var objImg = document.getElementsByName('ford').item(0);
objImg.style.height = h + 'px';
objImg.style.width = w + 'px';
}
You have two problems :
no will have the value of end of loop when the callback is called
you're programming all your timeouts 2000 ms from the same time, the time the loop run.
Here's how you could fix that :
var t = 0
while (no != 500) {
(function(no) {
t += 2000;
setTimeout(function() { size(no,no);} ,t);
})(no);
no = no+50; // could be written no += 50
}
The immediately executed function creates a scope which protects the value of no.
A little explanation about (function(no) { :
The scope of a variable is either
the global scope
a function
The code above could have been written as
var t = 0
while (no != 500) {
(function(no2) {
t += 2000;
setTimeout(function() { size(no2,no2);} ,t);
})(no);
no += 50;
}
Here it's probably more clear that we have two variables :
no, whose value changes with each iteration and is 500 when the timeouts are called
no2, in fact one variable no2 per call of the inner anonymous function
Each time the inner anonymous function is called, it declares a new no2 variable, whose value is no at the time of call (during iteration). This variable no2 is thus protected and is used by the callback given to setTimeout.
Why not just use setInterval() instead?
var objImg = new Object();
var h;
var w;
var no = 100;
var myInterval = window.setInterval(function() {
size(no, no);
no = no + 50;
if (no >= 500) clearInterval(myInterval);
}, 2000);
function size(h, w) {
var objImg = document.getElementsByName('ford').item(0);
objImg.style.height = h + 'px';
objImg.style.width = w + 'px';
}
Your problem is with your size() function syntax & algorithm:
var objImg = new Object();
var h;
var w;
var no = 100;
var int = window.setInterval(function () {
size(no,no);
no += 50;
},2000)
function size(h, w) {
if (h == 500){
window.clearInterval(int);
return;
}
var height = h + 'px';
var width = w + 'px';
document.getElementsByName('ford').item(0).style.height = height;
document.getElementsByName('ford').item(0).style.width = width;
}
http://jsfiddle.net/AQtNY/2/

Categories