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...
})()
I wanna create a slot machine with 3 number by javascript - but I want to finish my function when three numbers are equal.
I think that if I write it with do/while it will be work, but I can't do it
this is my js code:
function myF() {
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;
document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;
if(slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
}
}
this function is set onclick attr of a button tag
Adding to comment, if you want to run function for no of times then just use a counter variable to check no of attempts:
Added a reset button to reset the game.
var counter = 0;
function myF() {
if (counter != 5) {
counter++;
document.getElementById("slotLeft").innerHTML = "Try count: " + counter;
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;
document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;
if (slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
counter = 5; // Edited this line
}
} else {
console.log('Game over');
}
}
function myF1(){
counter = 0;
document.getElementById("slotOne").innerHTML = "";
document.getElementById("slotTwo").innerHTML = "";
document.getElementById("slotThree").innerHTML = "";
}
<button onclick="myF()">Check</button>
<button onclick="myF1()">Restart Game</button>
<div id="slotLeft">
</div>
<div id="slotOne">
</div>
<div id="slotTwo">
</div>
<div id="slotThree">
</div>
<div id="winner">
</div>
function myF() {
var slotOneElem = document.getElementById("slotOne");
var slotTwoElem = document.getElementById("slotTwo");
var slotThreeElem = document.getElementById("slotThree");
var generateRand = function() {
return Math.floor(Math.random() * 3) + 1;
}
return (function () {
var slotOne = generateRand();
var slotTwo = generateRand();
var slotThree = generateRand();
slotOneElem.innerHTML = slotOne;
slotTwoElem.innerHTML = slotTwo;
slotThreeElem.innerHTML = slotThree;
if (slotOne === slotTwo && slotTwo === slotThree) {
slotOneElem.style.backgroundColor = "#48bd48";
slotTwoElem.style.backgroundColor = "#48bd48";
slotThreeElem.style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
// Here is the win
return true;
}
return false;
})();
}
var finished = myF();
while (!finished) {
finished = myF();
}
I have this investment calculator in javascript/jquery. It calculates the profit someone would have, based on specific plans. It's written to work with bitcoin values, which goes like this 0.36000000 BTC. I just need to parse it to 3,6 format.
https://pastebin.com/DZvWxEkt
jQuery(function($){
//Setting calculator
var percent = [0.36,0.46,0.52];
var minMoney = [0.001,5.001, 10.001];
var maxMoney = [5,10,99999999.9999];
$("#btc_amt").val(minMoney[0]);
/*calculator*/
function calc(){
money = parseFloat($("#btc_amt").val());
id = -1;
var length = percent.length;
var i = 0;
do {
if(minMoney[i] <= money && money <= maxMoney[i]){
id = i;
i = i + length;
}
i++
}
while(i < length)
if(id != -1){
profitHourly = money / 100 * percent[id];
profitHourly = profitHourly.toFixed(8);
profitDaily = profitHourly * 24;
profitDaily = profitDaily.toFixed(8);
profitWeekly = profitDaily * 7;
profitWeekly = profitWeekly.toFixed(8);
profitMonthly = profitDaily * 30;
profitMonthly = profitMonthly.toFixed(8);
if(money < minMoney[id] || isNaN(money) == true){
$("#profitHourly").text("Error!");
$("#profitDaily").text("Error!");
$("#profitWeekly").text("Error!");
$("#profitMonthly").text("Error!");
//$("#total_profit").text("Error!");
} else {
$("#profitHourly").text(profitHourly + " BTC");
$("#profitDaily").text(profitDaily + " BTC");
$("#profitWeekly").text(profitWeekly + " BTC");
$("#profitMonthly").text(profitMonthly + " BTC");
//$("#total_profit").text(profitTotal + " BTC");
}
} else {
$("#profitHourly").text("Error!");
$("#profitDaily").text("Error!");
$("#profitWeekly").text("Error!");
$("#profitMonthly").text("Error!");
//$("#total_profit").text("Error!");
}
if(money >= 0.001 && money <= 5 ){
$('#active-plan').text('0.36% Hourly profit');
$("#h_id1").prop("checked", true);
}
if(money >= 5.001 && money <= 10 ){
$('#active-plan').text('0.46% Hourly profit');
$("#h_id2").prop("checked", true);
}
if(money >= 10.001 ){
$('#active-plan').text('0.52% Hourly profit');
$("#h_id3").prop("checked", true);
}
}
calc();
if($("#btc_amt").length){
calc();
}
$("#btc_amt").keyup(function(){
calc();
});
$("#h_id1").change(function(){
if ($(this).is(':checked')){
$('#btc_amt').val('0.001');
}
calc();
});
$("#h_id2").change(function(){
if ($(this).is(':checked')){
$('#btc_amt').val('5.001');
}
calc();
});
$("#h_id3").change(function(){
if ($(this).is(':checked')){
$('#btc_amt').val('10.001');
}
calc();
});
var clipboard = new Clipboard('.btn');
});
Got it working, thank you. Just changed the number of toFixed(n)
$.getJSON( "https://api.coindesk.com/v1/bpi/currentprice/usd.json",
function( data) {
var amountInBtc = 0.005; //convert 0.005 btc to usd
var exchangeRate = parseInt(data.bpi.USD.rate_float);
var amount = amountInBtc * exchangeRate;
console.log(amount);
});
Read the full post here
I have an assignment and I am a bit stuck. The assignment states:
Modify the game so that the time is tracked and a best time (or time to beat) is stored and displayed at the end of the game and at the beginning of the next game that is played. This functionality assumes the browser is not closed and that each successive game is begun through the "Play Again?" link. The display of the time to beat is shown below.
I have all files necessary, but I am stuck in this part. Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var placementArray = [];
var tileClicked;
var timeAllowable;
var totalMatchesPossible;
var matchesFound;
var txt;
var matchesFoundText;
var tileHeight = 30;
var tileWidth = 45;
var border = 1;
var globalPadding = 10;
var margin = 10;
var padding = 5;
var textTiles;
var flashcards = [
["a", "\u3042"],
["i", "\u3044"],
["u", "\u3046"],
["e", "\u3048"],
["o", "\u304A"],
["ka", "\u304B"],
["ki", "\u304D"],
["ku", "\u304F"],
["ke", "\u3051"],
["ko", "\u3053"],
["sa", "\u3055"],
["shi", "\u3057"],
["su", "\u3059"],
["se", "\u305B"],
["so", "\u305D"],
["ta", "\u305F"],
["chi", "\u3061"],
["tsu", "\u3064"],
["te", "\u3066"],
["to", "\u3068"],
["na", "\u306A"],
["ni", "\u306B"],
["nu", "\u306C"],
["ne", "\u306D"],
["no", "\u306E"],
["ha", "\u306F"],
["hi", "\u3072"],
["fu", "\u3075"],
["he", "\u3078"],
["ho", "\u307B"],
["ma", "\u307E"],
["mi", "\u307F"],
["mu", "\u3080"],
["me", "\u3081"],
["mo", "\u3082"],
["ya", "\u3084"],
["yu", "\u3086"],
["yo", "\u3088"],
["ra", "\u3089"],
["ri", "\u308A"],
["ru", "\u308B"],
["re", "\u308C"],
["ro", "\u308D"],
["wa", "\u308F"],
["wo", "\u3092"],
["n", "\u3093"]
];
function init() {
canvas = document.getElementById('myCanvas');
stage = new Stage(canvas);
totalMatchesPossible = flashcards.length;
var numberOfTiles = totalMatchesPossible * 2;
matchesFound = 0;
var columns = 12;
timeAllowable = 500;
txt = new Text(timeAllowable, "30px Monospace", "#000");
txt.textBaseline = "top";
txt.x = 700;
txt.y = 0;
stage.addChild(txt);
textTiles = [];
matchesFoundText = new Text(matchesFound + "/" + totalMatchesPossible, "30px Monospace", "#000");
matchesFoundText.textBaseline = "top";
matchesFoundText.x = 700;
matchesFoundText.y = 40;
stage.addChild(matchesFoundText);
Ticker.init();
Ticker.addListener(window);
Ticker.setPaused(false);
setPlacementArray(numberOfTiles);
for (var i = 0; i < numberOfTiles; i++) {
var placement = getRandomPlacement(placementArray);
var pairIndex = Math.floor(i / 2);
text = flashcards[pairIndex][i % 2];
var textTile = drawTextTile(text, pairIndex);
textTile.x = (tileWidth + margin) * (placement % columns) + globalPadding;
textTile.y = (tileHeight + margin) * Math.floor(placement / columns) + globalPadding;
stage.addChild(textTile);
background = new Shape();
background.x = textTile.x - padding;
background.y = textTile.y - padding;
background.graphics.setStrokeStyle(border).beginStroke("#000").beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
textTiles.push(background);
stage.addChildAt(background);
background.text = textTile;
background.onPress = handleOnPress;
stage.update();
};
}
function drawTextTile(text, pairIndex) {
textTile = new Text(text, "20px Monospace", "#000");
textTile.pairIndex = pairIndex;
textTile.textBaseline = "top";
return textTile;
}
function randomColor() {
var color = Math.floor(Math.random() * 255);
var color2 = Math.floor(Math.random() * 255);
var color3 = Math.floor(Math.random() * 255);
return Graphics.getRGB(color, color2, color3)
}
function setPlacementArray(numberOfTiles) {
for (var i = 0; i < numberOfTiles; i++) {
placementArray.push(i);
}
}
function getRandomPlacement(placementArray) {
randomNumber = Math.floor(Math.random() * placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event) {
var tile = event.target;
if (!!tileClicked === false || tileClicked === tile) {
tileClicked = tile;
} else {
tileClicked.graphics.beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
tile.graphics.beginFill('#aae').drawRect(0, 0, tileWidth, tileHeight);
if (tileClicked.text.pairIndex === tile.text.pairIndex && tileClicked.id != tile.id) {
tileClicked.visible = false;
tile.visible = false;
matchesFound++;
matchesFoundText.text = matchesFound + "/" + totalMatchesPossible;
if (matchesFound === totalMatchesPossible) {
gameOver(true);
}
}
tileClicked = tile;
}
stage.update();
}
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play Again?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
} else {
txt.text = secondsLeft + "... Game Over";
}
}
function replay() {
init();
}
</script>
</head>
<body onload="init()">
<header id="header">
<p id="replay"></p>
</header>
<canvas id="myCanvas" width="960" height="400"></canvas>
</body>
</html>
I give you 1 option for this, though you can do it also in other ways,
we declare global variables which are
var prev_time;
var best_time;
add that to your global variable declarations, then give it a value when you compute the time i guess we had that here:
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
//compute here the total time player had and give it to prev_time
//var totalTimePlayerplayed = some computation here which should be allowed time per player - secondsLeft
prev_time = totalTimePlayerplayed;
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play A
gain?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
if(best_time !== NULL){
best_time = prev_time;
//WE assume that the last player is the best scorer
}
} else {
//if there is already existing top scorer
if(best_time < prev_time){
best_time = prev_time
}
txt.text = secondsLeft + "... Game Over";
}
}
then give that time of the first player to the prev_time. Upon Game over or Game ended we validate here if the best_time has a value if not, then we give it a value of the value of prev_time, else we validate if the score is higher that the previous best_time and here's a tip, now when the player would trigger the "Play again" which I can't seem find right now, you get the variable best_time's value and display it as the score to beat. Hope you get the concept and somehow it helped you accomplished what you're intended to do, but like i said before you also have some other options to do this.
This question already has answers here:
Javascript seconds to minutes and seconds
(30 answers)
Closed 5 years ago.
var IDLE_TIMEOUT = 2700; //seconds 45min
var _idleSecondsCounter = 0;
document.onclick = function() {
_idleSecondsCounter = 0;
};
document.onmousemove = function() {
_idleSecondsCounter = 0;
};
document.onkeypress = function() {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
//alert("Your Session Time expired. Please Login.");
document.location.href = "logoff.php";
}
}
<div id='SecondsUntilExpire'></div>
So from above i am getting output as 2699 ( its in seconds = 45min ) and if no event happen its decrements ( 2698..2697..and so on ) and if any event (mouse up..etc ) happen its back to 2699
But i need in minutes thats : 44:59, 44:58 ..and so on
Use parseInt((IDLE_TIMEOUT - _idleSecondsCounter)/60) + ":" + (IDLE_TIMEOUT - _idleSecondsCounter)%60; to get achieve hh:mm effect
var IDLE_TIMEOUT = 2700; //seconds 45min
var _idleSecondsCounter = 0;
document.onclick = function() {
_idleSecondsCounter = 0;
};
document.onmousemove = function() {
_idleSecondsCounter = 0;
};
document.onkeypress = function() {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = parseInt((IDLE_TIMEOUT - _idleSecondsCounter)/60) + ":";
oPanel.innerHTML += (IDLE_TIMEOUT - _idleSecondsCounter)%60<10?"0"+(IDLE_TIMEOUT - _idleSecondsCounter)%60:(IDLE_TIMEOUT - _idleSecondsCounter)%60;
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
alert("Your Session Time expired. Please Login.");
//document.location.href = "logoff.php";
}
}
<div id='SecondsUntilExpire'></div>
Here's how I'd code it to be readable
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
var remain = IDLE_TIMEOUT - _idleSecondsCounter;
var remainMinutes = Math.floor(remain / 60);
var remainSeconds = ('0' + (remain % 60)).substr(-2);
if (oPanel)
oPanel.innerHTML = remainMinutes + ':' + remainSeconds;
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
//alert("Your Session Time expired. Please Login.");
document.location.href = "logoff.php";
}
}
uses
var remainSeconds = ('0' + (remain % 60)).substr(-2);
so that seconds are always two digits
Do you need this function
var IDLE_TIMEOUT = 2700;
alert(getMinutes(IDLE_TIMEOUT));
function getMinutes(time){
minutes = time/60;
seconds = time%60;
return ("00" + minutes).substr(-2)+":"+("00" + seconds).substr(-2);
}
Demo : https://jsfiddle.net/ttqtfwp5/1/