Mana regen upgrade set interval - javascript

After I press the Mp regen skill tree button it should minus 1 from skillpoints then add 1 to Manapoints. Then I need to store that then run a set interval thing but I can't get it to work correctly. My function seems ok but I can't replicate what I did in Python to work.
http://prntscr.com/nsm5yy
I'm not sure how to go about fixing this; I'm really new at set intervals. I did try this:
window.setInterval(function () {
ManaPointsregen(Mpregen);
}, 1000);
This is my JavaScript function for Manaregen (this is my second try with a different method but still can't get it to work):
var rebirths = 0;
var HitPoints = 0;
var MaxHitpoints = 10;
var ManaPoints = 0;
var MaxManapoints = 10;
var SkillPoints = 0;
function buyRebirth() {
var rebirthCost = Math.floor(10 * Math.pow(1.1, rebirths));
if (cookies >= rebirthCost && rebirths < 1){
cookies = cookies - rebirthCost
HitPoints = HitPoints + 10;
ManaPoints = ManaPoints + 10;
SkillPoints = SkillPoints + 1;
rebirths = rebirths + 1;
document.getElementById("rebirths").innerHTML = rebirths;
document.getElementById('cookies').innerHTML = cookies;
document.getElementById("HitPoints").innerHTML = HitPoints;
document.getElementById("ManaPoints").innerHTML = ManaPoints;
document.getElementById("rebirthCost").innerHTML = rebirthCost;
document.getElementById("SkillPoints").innerHTML = SkillPoints;
}
if (cookies >= rebirthCost)
if(rebirths >= 1){
cookies = cookies - rebirthCost
rebirths = rebirths + 1;
SkillPoints = SkillPoints +1;
document.getElementById('cookies').innerHTML = cookies;
document.getElementById("rebirthCost").innerHTML = rebirthCost;
document.getElementById("rebirths").innerHTML = rebirths;
document.getElementById("SkillPoints").innerHTML = SkillPoints;
}
var nextCost5 = Math.floor(10 * Math.pow(1.1, rebirths));
document.getElementById('rebirthCost').innerHTML = nextCost5;
}
var Mpregen = 0;
function Manaregen(){
if (ManaPoints < MaxManapoints && rebirths >- 1 && MaxManapoints >=0){
ManaPoints = ManaPoints +1;
set.interval( Manaregen, 1000);
}
document.getElementById("ManaPoints").innerHTML = ManaPoints;
}
function ManaPointsregenbuy(){
if (SkillPoints > 0 && rebirths >=1)
SkillPoints = SkillPoints - 1;
Mpregen = Mpregen +1;
set.interval(Manaregen, 1000);
document.getElementById("SkillPoints").innerHTML = SkillPoints;
document.getElementById("Mpregen").innerHTML = Mpregen;
}
JavaScript Setinverval:
var cookies = 0;
function cookieClick() {
cookies = cookies + Strength;
document.getElementById("cookies").innerHTML = cookies;
checkCursor()
}
var UP_INTERVAL = 1000;
setInterval(cookieClick, UP_INTERVAL);
html button code: (I'm not using the button Id for anything yet)
<button id="Mpreg" onclick="ManaPointsregenbuy">Mp regen</button>
<br />
I expect after buying a Mp regen from skill tree:
http://prntscr.com/nsmdmd
For my mana to go up by 1 every 1000ms (simulate mana regen) until it reaches My max mana. But the actual output the button does nothing. I have no idea how to set up a working setinterval function to do this.

The line
onclick="ManaPointsregenbuy"
should be
onclick="ManaPointsregenbuy()"
Then you have several lines like
set.interval(.....)
The correct syntax for setting an interval looks something like this
var myInterval = setInterval(callbackFunction, 1000);
This like will set an interval, that can be canceled with
clearInterval(myInterval)
You can find more info at https://www.w3schools.com/jsref/met_win_setinterval.asp

Related

Insert two scripts in the same <script> tag without conflicts

I have to put these two scripts in a single tag without them coming into conflict but I can not make it. Please, how can I do it?
Also is it better to insert multiple scripts in the same tag?
Script 1
var sec = 04;
var hour = 00;
var time0, time1;
var delay=0;
var duringtime = 1000;
time1 = (hour *10000 + min * 100 + parseInt(sec)).toString();
console.log("time1", time1);
function refresh() {
........
}
}
refresh();
Script 2
var min = 80;
var max = 85;
var random = Math.floor(Math.random() * (max - min)) + min;
if (localStorage.getItem("stockcount_99")) {
if (localStorage.getItem("stockcount_99") >= duration) {
var value = random;
} else {
var value = localStorage.getItem("stockcount_99");
}
} else {
var value = random;
}
document.getElementById('divCounter').innerHTML = value;
var stockcount_99 = function() {
if (value <= stopValue) { // end count down. <= or >=
clearInterval(interval);
value = stopValue;
} else {
value = parseInt(value) - 1; // + 1 or - 1
localStorage.setItem("stockcount_99", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function() {
stockcount_99();
}, speedcontrol);
With the following method can I isolate the two scripts and thus prevent any conflicts?
(function() {
...script 1...
})()
(function() {
...script 2...
})()

Increment issues

I have a timer going that adds 1 every second to the variable MenuTimer.
What I want is when the next button is pressed TillOpen The MenuTimer will stop having 1 added to it after that and a new variable to have 1 added instead PackTime
window.onload = function () {
var StopwatchSeconds= 00;
var StopwatchMinutes = 00;
var ShowSeconds = document.getElementById("seconds");
var ShowMinutes = document.getElementById("minutes");
var StartButton = document.getElementById("ButtonStart");
var Interval;
var menuTime;
var serviceTime;
var orders;
var menuAvg;
var serviceAvg;
StartButton.onclick= function(){
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
}
function startTimer () {
StopwatchSeconds++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
ShowMinutes.innerHTML = StopwatchMinutes;
StopwatchMinutes++;
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
}
}
Here's all of it. It half works but hopefully you get a better Idea of what i'm trying to go for.
var Interval;
var PackInterval;
var StopwatchSeconds= 00;
var StopwatchMinutes = 00;
var ShowSeconds = document.getElementById("seconds");
var ShowMinutes = document.getElementById("minutes");
var StartButton = document.getElementById("ButtonStart");
var TillOpenButton = document.getElementById("TillOpen");
var FinishButton = document.getElementById("Finish");
var ShowMenuTime = document.getElementById("MenuTime");
var ShowPackTime = document.getElementById("PackTime");
var ShowPackAvgSeconds = document.getElementById("PackerSeconds");
var ShowPackAvgMinutes = document.getElementById("PackerMinutes");
var ShowMenuAvgSeconds = document.getElementById("MenuMinutes");
var ShowMenuAvgMinutes = document.getElementById("MenuSeconds");
var DivisionSeconds = 60;
var TotalTime = 0;
var MenuTime = 0;
var PackTime = 0;
var AllMenuTimes = 0;
var AllPackTimes = 0;
var TotalMenuOrders = 0;
var TotalPackOrders = 0;
var MenuOrdersTotalSeconds = 0;
var PackOrdersTotalSeconds = 0;
var MenuAvgMinutes = 0;
var MenuAvgSeconds = 0;
var PackAvgSeconds = 0;
var PackAvgMinutes = 0;
StartButton.onclick = function(){
TotalMenuOrders + 1;
MenuTime = 0;
ShowMenuTime.innerHTML = MenuTime;
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
window.alert ("I work");
}
//This starts the timer. Inverval is a variable that holds the timer number.
function startTimer () {
StopwatchSeconds++;
TotalTime++;
MenuTime++;
AllMenuTime++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
StopwatchMinutes++;
ShowMinutes.innerHTML = StopwatchMinutes; // Makes this a string in html
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
}
// When the start button is pressed this function starts. it adds 1 to
Stopwatch, total and Menu every 1000 increments that Interval hits.
// This also says if StopwatchSeconds goes above 59 itll reset to 0 and if
its below itll keep counting.
TillOpenButton.onclick = function () {
PackTime = 0;
ShowPackTime.innerHTML = PackTime;
ShowMenuTime.innerHTML = MenuTime;
PackInterval = setInterval(startPackerTimer, 1000);
Interval+PackInterval;
clearInterval(Interval);
/* if (TotalMenuOrders < 1) {
AllMenuTimes / TotalMenuOrders = MenuOrdersTotalSeconds;
MenuOrderTotalSeconds % 60 = MenuAvgSeconds;
MenuAvgMinutes = Math.floor(MenuOrderTotalSeconds/60);
ShowMenuAvgMinutes.innerHTML = MenuAvgMinutes;
ShowMenuAvgSeconds.innerHTML = MenuAvgSeconds;
}
*/
}
// When this button is pressed it stops the first timer and the menu timer.
It then starts a new timer and function which add to the variable that will
show the total time.
// It does clear the variable Interval though
FinishButton.onclick = function (){
clearInterval(Interval);
ShowPackTime.innerHTML = PackTime;
clearInterval(PackInterval);
StopwatchSeconds = 0;
StopwatchMinutes = 0;
ShowSeconds.innerHTMl = 0 + StopwatchSeconds;
ShowMinutes.innerHTML = 0 + StopwatchMinutes;
AllPackTimes += PackTime;
TotalPackOrders++;
/*AllPackTimes/TotalPackOrders = PackOrderTotalSeconds;
PackOrderTotalSeconds % DivisionSeconds = PackAvgSeconds;
PackAvgMinutes = Math.floor(PackOrderTotalSeconds/60);
ShowPackAvgMinutes.innerHTML = PackAvgMinutes;
ShowPackAvgSeconds.innerHTML = PackAvgSeconds;*/
}
// When the Finish Button is pressed it clears everything. Resets
everything. except Menu Time, Total Time and PackTime. I need 3 new
variables to hold these to get the average.
function startPackerTimer () {
StopwatchSeconds++;
TotalTime++;
PackTime++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
StopwatchMinutes++;
ShowMinutes.innerHTML = StopwatchMinutes;
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
// Same deal but with the Till open button. Still adds onto
STopwatchSeconds so the variable doesn't change.
}
New solution, wich allows to create different timers and keep track of them:
//a method to setup a new timer
function Timer(Name){
this.timeElement=document.createElement("div");
(this.stopButton=document.createElement("button")).innerHTML="STOP";
(this.startButton=document.createElement("button")).innerHTML="START";
(this.Name=document.createElement("h1")).innerHTML=Name;
[this.Name,this.timeElement,this.startButton,this.stopButton].forEach(el=>document.body.appendChild(el));
this.stopButton.addEventListener("click",this.stop.bind(this));
this.startButton.addEventListener("click",this.start.bind(this));
this.seconds=0;
this.minutes=0;
}
Timer.prototype={
update:function() {
this.seconds++;
if(this.seconds > 59) {
this.seconds=0;
this.minutes++;
}
var secTemp="00"+this.seconds, minTemp="00"+this.minutes;
this.timeElement.innerHTML=minTemp.slice(minTemp.length-2)+":"+secTemp.slice(secTemp.length-2);
},
stop:function(){
if(this.interval) clearInterval(this.interval);
this.running=false;
if(this.onstop) this.onstop(this);
}
start:function(){
if(this.interval) clearInterval(this.interval);
this.interval = setInterval(this.update.bind(this), 1000);
this.running=true;
if(this.onstart) this.onstart(this);
}
};
This implements a Timer with OOP. So you can create multiple timers, and they wont influence each other.
You can create a timer like this:
var timer= new Timer("The Name");
You can also change events, set/read the times and check if running:
timer.start();//start the timer ( can also be done with the ui button)
timer.stop();
timer.onstart=()=>alert("Started!");
timer.onstop=()=>alert("Stopped!");
console.log(timer.running,timer.minutes,timer.seconds);
If you want to wait for multiple timers and to calculate the average if all of them stopped:
var timers=["Timer 1", "Timer 2"].map(name=>new Timer(name));//create two timers and store in array
timers.forEach(function(timer){
timer.running=true;
timer.onstop=function(){
if(timers.some(t=>t.running)) return;//if theres a running timer dont procceed
var seconds=timers.reduce((seconds,timer)=>seconds+=(timer.seconds+timer.minutes*60),0);
var average=seconds/timers.length;
alert("Average: "+average+"s");
};
});
http://jsbin.com/coduvohewu/edit?output
The old solution, adding a timer if the new button is pressed, and stops the old one then:
So you want to stop the current timer, and create a new one below that? Maybe you could refactor the code a bit, doing sth like this:
window.onload = function () {
var seconds= 0,minutes = 0;
var times=[];
var Interval;
var timeElement;
//a method to setup a new timer
function createTimer(dontsave){
if(times.length>3) return alert(times.map(el=>el.join(":")).join());
timeElement=document.createElement("div");
document.body.appendChild(timeElement);
if(!dontsave) times.push([minutes,seconds]);
}
createTimer(true);
//a method to let the timer run
function startTimer () {
seconds++;
if(seconds > 59) {
seconds=0;
minutes++;
}
var secTemp="00"+seconds,minTemp="00"+minutes;
timeElement.innerHTML=minTemp.slice(minTemp.length-2)+":"+secTemp.slice(secTemp.length-2);
}
//assign to buttons:
document.getElementById("ButtonStart").onclick= function(){
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
}
document.getElementById("ButtonNew").onclick=createTimer;
};
http://jsbin.com/mujisaweyo/edit?output
This simply creates a new div in the DOM if you press a button with the id ButtonNew . So the current time stays as a text in the old Element, and it keeps counting in the new one. Ive also added a zero filling...

How to change amount variable is incremented by in JavaScript?

!NO JQUERY!
Ok, so I am making a game for my friends based on cookie clicker game from years ago and my issue is I want to increase what the clicks are incremented by when I click a multiplier button.
Basically, when the user reaches 100 clicks and if they click on the multiplier button it will increase the increment by 1.
The cpcm function function cpcm(){cl1ck5m = 1;} will increase cl1ck5m by 1 when the user clicks the multiplier button. I want to add this value to the main increment total = cl1ck +=1; in the function cl1ckm8() {} only if the user clicks the multiplier button when they reach 100 clicks.
I dont know how I would do this.
var cl1ck5 = 0;
var total = 0;
var cl1ck5m = 0;
var rotated = false;
window.alert("H3lp C00ki3 Man3st3r!\nCan y0u h3lp C00ki3 Man3st3r c0ll3ct c00ki3s?");
function cl1ckm8() {
total = cl1ck +=1;
document.getElementById('cl1ckC0unt').innerHTML = total;
if (cl1ck5 == 90) {
var div = document.getElementById('butt');
var deg = rotated ? 0 : 90;
var msg = document.getElementById("ache");
msg.innerHTML = "nineD d3gr33s";
div.style.transform = 'rotate('+deg+'deg)';
}
if (cl1ck5 == 100) {
var div = document.getElementById('cpcbutt');
div.innerHTML = "1";
}
}
function cpcm(){
cl1ck5m = 1;
}
I'm not sure what you're asking but anyway...
var multiplierButtonClicked = false;
document.getElementById("multiplier").onclick = function(){
if (cl1ck5 >= 100)
multiplierButtonClicked=true;
}
function cl1ckm8()
{
total = cl1ck +=1;
if (multiplierButtonClicked)
total += cl1ck5m;
//...
}
function cpcm(){
if (multiplierButtonClicked)
cl1ck5m += 1;
}
I fixed it. Thanks for any help.
I simply put the multiplier in place of the 1 in total = cl1ck +=1; like total = cl1ck +=cl1ckm;. I was trying to avoid this way to find other ways of doing it but this works best.

Time function, find a better solution

I have made this time and date function with a bunch of if else statements. But is there a better way to do this? I think it uses a lot of processor power.
The function increments time. Each number is a var. So in seconds we have single seconds (sec) and tens of seconds (tensec).
check out the jsfiddle here: http://jsfiddle.net/MLgbs/1/
$seconds = $('.seconds .one');
$tenseconds = $('.seconds .ten');
$minutes = $('.minutes .one');
$tenminutes = $('.minutes .ten');
$hours = $('.hours .one');
$tenhours = $('.hours .ten');
$days = $('.days .one');
$tendays = $('.days .ten');
$months = $('.months .one');
$tenmonths = $('.months .ten');
$years = $('.years .one');
$tenyears = $('.years .ten');
$houndredyears = $('.years .houndred');
var sec = 0;
var tensec = 0;
var min = 0;
var tenmin = 0;
var hours = 0;
var tenhours = 0;
var days = 0;
var tendays = 0;
var months = 0;
var tenmonths = 0;
var years = 0;
var tenyears = 0;
var houndredyears = 0;
function clock(){
//Seconds
if(sec < 9){
sec++;
console.log($seconds, sec);
} else {
sec = 0;
console.log($seconds, sec);
//Tenseconds
if(tensec<5){
tensec++;
console.log($tenseconds, tensec);
} else {
tensec = 0;
console.log($tenseconds, tensec);
//minutes
if(min<9){
min++;
console.log($minutes, min);
} else {
min = 0;
console.log($minutes, min);
//tenminutes
if(tenmin<5){
tenmin++;
console.log($tenminutes, tenmin);
} else {
tenmin=0;
console.log($tenminutes, tenmin);
//hours
if(hours<9 && (tenhours*10+hours<23)){
hours++;
console.log($hours, hours);
} else {
hours=0;
console.log($hours, hours);
//tenhours
if(tenhours<2 && (tenhours*10+hours<23)){
tenhours++;
console.log($tenhours, tenhours);
} else {
tenhours=0;
console.log($tenhours, tenhours);
if(days < 9 && (tendays*10+days<30)){
days++;
console.log($days, days);
} else {
if(days !== 0){
days = 0;
console.log($days, days);
}
if(tendays<2){
tendays++;
console.log($tendays, tendays);
} else {
tendays = 0;
console.log($tendays, tendays);
if(months<9 && (tenmonths*10+months<11)){
months++;
console.log($months, months);
} else {
months = 0;
console.log($months, months);
if(tenmonths<0){
tenmonths++;
console.log($tenmonths, tenmonths);
} else {
tenmonths = 0;
console.log($tenmonths, tenmonths);
if(years < 9){
years++;
console.log($years, years);
} else {
years = 0;
console.log($years, years);
if(tenyears<9){
tenyears++;
console.log($tenyears, tenyears);
} else {
tenyears = 0;
console.log($tenyears, tenyears);
if(houndredyears<9){
houndredyears++;
console.log($houndredyears, houndredyears);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
setInterval(function(){clock();},1000);
Why don't you just use the Date() object? Rather than all this calculation, simply pull the time from it at regular intervals (several per second, say), and display that - that way, it will be synced to the time on the client computer, rather than the inaccurate setInterval function, which will probably not give an accurate reflection of the time after very long (especially given all the legwork you're making it do with a dozen or so nested conditions!)
If you have multiple users who all require reference to a common clock, use PHP to get the date instead - this will return the server date/clock, instead of the client.

DHTML - Show picture for limited time

im try to use DHTML in order to make animation for 3-5 sec( the anumation supose to start from the left to the right...).
any idea how to do tthat???
//this one will set the the pictue on the right side of the screen
function setUpPicture() {
subRunnerOBJ = new Object();
subRunnerOBJ.topPos = 100;
subRunnerOBJ.leftPos = 0;
subRunnerOBJ.velX = 400;
subRunnerOBJ.velY = 0;
subRunnerOBJ.score = 0;
hide1.style.visibility = "visible";
hide1.style.left = subRunnerOBJ.leftPos + "px";
hide1.style.top = subRunnerOBJ.topPos + "px";
hide1.style.position = "absolute";
//once we place the location of the sub , we will Call to new function that will move it
startMovePicture();
}
function startMovePicture() {
dt = 50; // in miliseconds
h = setInterval("moveObj(subRunnerOBJ)", dt);
}
function moveObj(someObj) {
counter = 0;
while (counter < 30000) {
subRunnerOBJ.leftPos = subRunnerOBJ.leftPos + subRunnerOBJ.velX * dt / 1000;
subRunnerOBJ.topPos = subRunnerOBJ.topPos + subRunnerOBJ.velY * dt / 1000;
hide1.style.left = subRunnerOBJ.leftPos + "px";
hide1.style.top = subRunnerOBJ.topPos + "px";
counter = counter + 50;
if (counter == 3000) {
stopRunning();
}
}
}
function stopRunning() {
clearInterval(h);
hide1.style.visibility = "hidden";
}
with this function i can see the picture for less than a sec...
how can i set the time here??
Replace the milliseconds value with a number equal to the desired number of seconds, which would be 5000 for five seconds. Remove the while loop inside of moveObj and replace it by adding clearInterval(h) and hide1.style.visibility = "hidden"; as the last statement inside that block.

Categories