Need that, the counter should be start after button click, when start count up - start button must be inactive, after count up finish - button must be active and have someone function.
var refDate = new Date("2013 01 18 16:41");
var prepend = "This is a message ";
var append = new Date(refDate).toLocaleString();
var refValue = "1,100.00";
function insertCommas(nAmt) {
var currAmt = nAmt.toFixed(2);
while (/(\d+)(\d{3})/.test(currAmt)) {
currAmt = currAmt.replace(/(\d+)(\d{3})/, "$1,$2");
}
return currAmt;
}
function dispCounter() {
var currDate = new Date();
var elapsedSeconds = Math.round((refDate - currDate) / 100);
var elapsedValue = elapsedSeconds / 100;
var nRef = refValue.replace(/\,/g, "");
var result = insertCommas(nRef - elapsedValue);
document.getElementById('upCount').innerHTML = prepend + " $" + result + " since " + append;
setTimeout("dispCounter()", 1500);
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', dispCounter, false) : addEventListener('load', dispCounter, false);
Related
Can some body help me modify this script.
The purpose of the script is to change bids for the keywords based on average position. One of the assumptions that the script has is that it sets a firstpagebid for the keyword but it won't allow for the bid to go below the firstpagebid even if the position is too high.
Is there a way to remove this restriction? so basically if the new cpc calculated is lower than the first page bid then it allows for the new cpc to be lower than the firstpage bid.
/**
*
* Average Position Bidding Tool
*
* This script changes keyword bids so that they target specified positions,
* based on recent performance.
*
* Version: 1.5
* Updated 2015-09-28 to correct for report column name changes
* Updated 2016-02-05 to correct label reading, add extra checks and
* be able to adjust maximum bid increases and decreases separately
* Updated 2016-08-30 to correct label reading from reports
* Updated 2016-09-14 to update keywords in batches
* Updated 2016-10-26 to avoid DriveApp bug
* Google AdWords Script maintained on brainlabsdigital.com
*
**/
// Options
var maxBid = 14.50;
// Bids will not be increased past this maximum.
var minBid = 3.0;
// Bids will not be decreased below this minimum.
var firstPageMaxBid = 10.00;
// The script avoids reducing a keyword's bid below its first page bid estimate. If you think
// Google's first page bid estimates are too high then use this to overrule them.
var dataFile = "AveragePositionData.txt";
// This name is used to create a file in your Google Drive to store today's performance so far,
// for reference the next time the script is run.
var useFirstPageBidsOnKeywordsWithNoImpressions = true;
// If this is true, then if a keyword has had no impressions since the last time the script was run
// its bid will be increased to the first page bid estimate (or the firsPageMaxBid if that is smaller).
// If this is false, keywords with no recent impressions will be left alone.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Advanced Options
var bidIncreaseProportion = 0.20;
var bidDecreaseProportion = 0.25;
var targetPositionTolerance = 0.3;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function main() {
var fieldJoin = ",";
var lineJoin = "$";
var idJoin = "#";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*var files = DriveApp.getFilesByName(dataFile);
if (!files.hasNext()) {
var file = DriveApp.createFile(dataFile,"\n");
Logger.log("File '" + dataFile + "' has been created.");
} else {
var file = files.next();
if (files.hasNext()) {
Logger.log("Error - more than one file named '" + dataFile + "'");
return;
}
Logger.log("File '" + dataFile + "' has been read.");
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Get the current date/time
var currentTime = new Date(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "MMM dd,yyyy HH:mm:ss"));
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var hourOfDay = currentTime.getHours();
var dayOfWeek = days[currentTime.getDay()]; //Added on 9/21/2015
// Prevent adjustments if not in between 8am and 11pm and Diffrent running time by date - Added on 9/21/2015 (important allows to set time based on day)
switch (dayOfWeek) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
if (hourOfDay < 8 || hourOfDay >= 21) {
Logger.log("Not the Right Time");
return;
}
break;
case 'Saturday':
case 'Sunday':
if (hourOfDay < 8 || hourOfDay >= 18) {
Logger.log("Not the Right Time");
return;
}
break;
}
Logger.log("Right Time");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var labelIds = [];
var labelIterator = AdWordsApp.labels()
.withCondition("KeywordsCount > 0")
.withCondition("LabelName CONTAINS_IGNORE_CASE 'Position '")
.get();
while (labelIterator.hasNext()) {
var label = labelIterator.next();
if (label.getName().substr(0,"position ".length).toLowerCase() == "position ") {
labelIds.push(label.getId());
}
}
if (labelIds.length == 0) {
Logger.log("No position labels found.");
return;
}
Logger.log(labelIds.length + " position labels have been found.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var keywordData = {
//UniqueId1: {LastHour: {Impressions: , AveragePosition: }, ThisHour: {Impressions: , AveragePosition: },
//CpcBid: , FirstPageCpc: , MaxBid, MinBid, FirstPageMaxBid, PositionTarget: , CurrentAveragePosition:,
//Criteria: }
}
var ids = [];
var uniqueIds = [];
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var report = AdWordsApp.report(
'SELECT Id, Criteria, AdGroupId, AdGroupName, CampaignName, Impressions, AveragePosition, CpcBid, FirstPageCpc, Labels, BiddingStrategyType ' +
'FROM KEYWORDS_PERFORMANCE_REPORT ' +
'WHERE Status = ENABLED AND AdGroupStatus = ENABLED AND CampaignStatus = ENABLED ' +
'AND LabelIds CONTAINS_ANY [' + labelIds.join(",") + '] ' +
'AND AdNetworkType2 = SEARCH ' +
'AND Device NOT_IN ["HIGH_END_MOBILE"] ' +
'DURING TODAY'
);
var rows = report.rows();
while(rows.hasNext()){
var row = rows.next();
if (row["BiddingStrategyType"] != "cpc") {
if (row["BiddingStrategyType"] == "Enhanced CPC"
|| row["BiddingStrategyType"] == "Target search page location"
|| row["BiddingStrategyType"] == "Target Outranking Share"
|| row["BiddingStrategyType"] == "None"
|| row["BiddingStrategyType"] == "unknown") {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses '" + row["BiddingStrategyType"] + "' rather than manual CPC. This may overrule keyword bids and interfere with the script working.");
} else {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses the bidding strategy '" + row["BiddingStrategyType"] + "' rather than manual CPC. This keyword will be skipped.");
continue;
}
}
var positionTarget = "";
if (row["Labels"].trim() == "--") {
continue;
}
var labels = JSON.parse(row["Labels"].toLowerCase()); // Labels are returned as a JSON formatted string
for (var i=0; i<labels.length; i++) {
if (labels[i].substr(0,"position ".length) == "position ") {
var positionTarget = parseFloat(labels[i].substr("position ".length-1).replace(/,/g,"."),10);
break;
}
}
if (positionTarget == "") {
continue;
}
if (integrityCheck(positionTarget) == -1) {
Logger.log("Invalid position target '" + positionTarget + "' for keyword '" + row["Criteria"] + "' in campaign '" + row["CampaignName"] + "'");
continue;
}
ids.push(parseFloat(row['Id'],10));
var uniqueId = row['AdGroupId'] + idJoin + row['Id'];
uniqueIds.push(uniqueId);
keywordData[uniqueId] = {};
keywordData[uniqueId]['Criteria'] = row['Criteria'];
keywordData[uniqueId]['ThisHour'] = {};
keywordData[uniqueId]['ThisHour']['Impressions'] = parseFloat(row['Impressions'].replace(/,/g,""),10);
keywordData[uniqueId]['ThisHour']['AveragePosition'] = parseFloat(row['AveragePosition'].replace(/,/g,""),10);
keywordData[uniqueId]['CpcBid'] = parseFloat(row['CpcBid'].replace(/,/g,""),10);
keywordData[uniqueId]['FirstPageCpc'] = parseFloat(row['FirstPageCpc'].replace(/,/g,""),10);
setPositionTargets(uniqueId, positionTarget);
}
Logger.log(uniqueIds.length + " labelled keywords found");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
setBidChange();
setMinMaxBids();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/* var currentHour = parseInt(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "HH"), 10);
if (currentHour != 0) {
var data = file.getBlob().getDataAsString();
var data = data.split(lineJoin);
for(var i = 0; i < data.length; i++){
data[i] = data[i].split(fieldJoin);
var uniqueId = data[i][0];
if(keywordData.hasOwnProperty(uniqueId)){
keywordData[uniqueId]['LastHour'] = {};
keywordData[uniqueId]['LastHour']['Impressions'] = parseFloat(data[i][1],10);
keywordData[uniqueId]['LastHour']['AveragePosition'] = parseFloat(data[i][2],10);
}
}
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
findCurrentAveragePosition();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Batch the keyword IDs, as the iterator can't take them all at once
var idBatches = [];
var batchSize = 5000;
for (var i=0; i<uniqueIds.length; i += batchSize) {
idBatches.push(uniqueIds.slice(i,i+batchSize));
}
Logger.log("Updating keywords");
// Update each batch
for (var i=0; i<idBatches.length; i++) {
try {
updateKeywords(idBatches[i]);
} catch (e) {
Logger.log("Error updating keywords: " + e);
Logger.log("Retrying after one minute.");
Utilities.sleep(60000);
updateKeywords(idBatches[i]);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Logger.log("Writing file.");
// var content = resultsString();
// file.setContent(content);
Logger.log("Finished.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function integrityCheck(target){
var n = parseFloat(target, 10);
if(!isNaN(n) && n >= 1){
return n;
}
else{
return -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setPositionTargets(uniqueId, target){
if(target !== -1){
keywordData[uniqueId]['HigherPositionTarget'] = Math.max(target-targetPositionTolerance, 1);
keywordData[uniqueId]['LowerPositionTarget'] = target+targetPositionTolerance;
}
else{
keywordData[uniqueId]['HigherPositionTarget'] = -1;
keywordData[uniqueId]['LowerPositionTarget'] = -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function bidChange(uniqueId){
var newBid = -1;
if(keywordData[uniqueId]['HigherPositionTarget'] === -1){
return newBid;
}
var cpcBid = keywordData[uniqueId]['CpcBid'];
var minBid = keywordData[uniqueId]['MinBid'];
var maxBid = keywordData[uniqueId]['MaxBid'];
if (isNaN(keywordData[uniqueId]['FirstPageCpc'])) {
Logger.log("Warning: first page CPC estimate is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
var firstPageBid = Math.min(keywordData[uniqueId]['FirstPageCpc'], keywordData[uniqueId]['FirstPageMaxBid'], maxBid);
var currentPosition = keywordData[uniqueId]['CurrentAveragePosition'];
var higherPositionTarget = keywordData[uniqueId]['HigherPositionTarget'];
var lowerPositionTarget = keywordData[uniqueId]['LowerPositionTarget'];
var bidIncrease = keywordData[uniqueId]['BidIncrease'];
var bidDecrease = keywordData[uniqueId]['BidDecrease'];
if((currentPosition > lowerPositionTarget) && (currentPosition !== 0)){
var linearBidModel = Math.min(2*bidIncrease,(2*bidIncrease/lowerPositionTarget)*(currentPosition-lowerPositionTarget));
var newBid = Math.min((cpcBid + linearBidModel), maxBid);
}
if((currentPosition < higherPositionTarget) && (currentPosition !== 0)) {
var linearBidModel = Math.min(2*bidDecrease,((-4)*bidDecrease/higherPositionTarget)*(currentPosition-higherPositionTarget));
var newBid = Math.max((cpcBid-linearBidModel),minBid);
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
}
if((currentPosition === 0) && useFirstPageBidsOnKeywordsWithNoImpressions && (cpcBid < firstPageBid)){
var newBid = firstPageBid;
}
if (isNaN(newBid)) {
Logger.log("Warning: new bid is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
return newBid;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function findCurrentAveragePosition(){
for(var x in keywordData){
if(keywordData[x].hasOwnProperty('LastHour')){
keywordData[x]['CurrentAveragePosition'] = calculateAveragePosition(keywordData[x]);
} else {
keywordData[x]['CurrentAveragePosition'] = keywordData[x]['ThisHour']['AveragePosition'];
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function calculateAveragePosition(keywordDataElement){
var lastHourImpressions = keywordDataElement['LastHour']['Impressions'];
var lastHourAveragePosition = keywordDataElement['LastHour']['AveragePosition'];
var thisHourImpressions = keywordDataElement['ThisHour']['Impressions'];
var thisHourAveragePosition = keywordDataElement['ThisHour']['AveragePosition'];
if(thisHourImpressions == lastHourImpressions){
return 0;
}
else{
var currentPosition = (thisHourImpressions*thisHourAveragePosition-lastHourImpressions*lastHourAveragePosition)/(thisHourImpressions-lastHourImpressions);
if (currentPosition < 1) {
return 0;
} else {
return currentPosition;
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function keywordUniqueId(keyword){
var id = keyword.getId();
var idsIndex = ids.indexOf(id);
if(idsIndex === ids.lastIndexOf(id)){
return uniqueIds[idsIndex];
}
else{
var adGroupId = keyword.getAdGroup().getId();
return adGroupId + idJoin + id;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setMinMaxBids(){
for(var x in keywordData){
keywordData[x]['MinBid'] = minBid;
keywordData[x]['MaxBid'] = maxBid;
keywordData[x]['FirstPageMaxBid'] = firstPageMaxBid;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setBidChange(){
for(var x in keywordData){
keywordData[x]['BidIncrease'] = keywordData[x]['CpcBid'] * bidIncreaseProportion/2;
keywordData[x]['BidDecrease'] = keywordData[x]['CpcBid'] * bidDecreaseProportion/2;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function updateKeywords(idBatch) {
var keywordIterator = AdWordsApp.keywords()
.withIds(idBatch.map(function(str){return str.split(idJoin);}))
.get();
while(keywordIterator.hasNext()){
var keyword = keywordIterator.next();
var uniqueId = keywordUniqueId(keyword);
var newBid = bidChange(uniqueId);
if(newBid !== -1){
keyword.setMaxCpc(newBid);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*function resultsString(){
var results = [];
for(var uniqueId in keywordData){
var resultsRow = [uniqueId, keywordData[uniqueId]['ThisHour']['Impressions'], keywordData[uniqueId]['ThisHour']['AveragePosition']];
results.push(resultsRow.join(fieldJoin));
}
return results.join(lineJoin);
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
}
As I understand, the script increases the cpcBid when the current average position is too high, and decreases it when the position is too low.
But when the bid is decreased and the previous bid is more than firstPageBid, the new bid will not decrease below firstPageBid.
Remove
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
to allow your new bid to go lower than firstPageBid.
There is a variable which contains event time. I want to redirect user if event time + 04:38 is more than current time.
Below is the code i have tried:
var deadline = getDayInstance("Monday","08:00:59")
function getDayInstance(day,time) {
const days = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,"Friday":5,"Saturday":6};
if(days[day]!==undefined)
var dayINeed = days[day];
else
var dayINeed = 2; // for Tuesday
const today = moment().tz("America/Los_Angeles").isoWeekday();
var dt;
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
dt = moment().tz("America/Los_Angeles").isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
else {
dt = moment().tz("America/Los_Angeles").add(1, 'weeks').isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
console.log("Event Time: "+dt);
var maxLimit = Date.parse(moment(time,'HH:mm:ss').tz("America/Los_Angeles").add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
var now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit < now)
{
dt = moment().tz("America/Los_Angeles").add(1, 'weeks').isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
window.setVideo = false;
}
console.log(moment(time,'HH:mm:ss').tz("America/Los_Angeles").add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
console.log(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
return dt;
}
var maxLimit = Date.parse(moment(deadline,'YYYY-MM-DDTHH:mm:ss').add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
var now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit>=now){
var redirectTo = $("#lp-pom-button-673").attr('href');
if(redirectTo.length > 3){
window.location.href = redirectTo;
}
else{
window.location.href = "https://******/";
}
}
I need to maintain timezone in calculation.
I got the answer of this after refining the process theoretically and then try to implement it in JS. Below is the new code that can be used for this.
var deadline = getDayInstance("Tuesday", "02:32:00");
var maxLimit,now;
function getDayInstance(day,time) {
const days = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,
"Friday":5,"Saturday":6};
if(days[day]!==undefined)
var dayINeed = days[day];
else
var dayINeed = 2; // for Tuesday
const today = moment().tz("America/Los_Angeles").isoWeekday();
var dt;
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
dt = moment().tz("America/Los_Angeles").isoWeekday(dayINeed)
.format('YYYY-MM-DD')+"T"+time;
}
else {
dt = moment().tz("America/Los_Angeles").add(1, 'weeks')
.isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
var d = new Date(dt);
d.setHours(d.getHours() + 4);
d.setMinutes(d.getMinutes() + 43);
d.setSeconds(d.getSeconds() + 32);
max = Date.parse(d);
now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit < now)
{
dt = moment().tz("America/Los_Angeles").add(1, 'weeks')
.isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
return dt;
}
if(maxLimit>=now){
var redirectTo = $("#lp-pom-button-673").attr('href');
if(redirectTo.length > 3){
window.location.href = redirectTo;
}
else{
window.location.href = "https://******/";
}
}
Im trying to make an online Role Playing Game, but my code is not working. It asks the user what they want their character to be named, and what race they want to be. It would then randomly choose some stats for them, and -- depending upon their race -- add and subtract from their stats.
var nameAndRaceFunction = function(){
var namePrompt = prompt("What shall you name your character?");
var racePrompt = prompt("What race shall your character be? Please spell it correctly, with no capitals.");
var race = racePrompt.toLowerCase();
var totalSentence = namePrompt + " the " + race;
document.getElementById("nameAndRace").innerHTML = totalSentence;
}
var str = Math.floor((Math.random() * 10) + 1);
var int = Math.floor((Math.random() * 10) + 1);
var hlth = Math.floor((Math.random() * 10) + 1);
var dext = Math.floor((Math.random() * 10) + 1);
var getStatFunction = function(){
if(racePrompt === "elf"){
elfStats();
}else if(racePrompt === "dwarf"){
dwarfStats();
}else if(racePrompt === "man"){
manStats();
}else{
}
}
var elfStats = function(){
var elfStr = str;
var elfInt = int + 1;
var elfHlth = (hlth - 1)*10;
var elfDext = dext + 1;
document.getElementById("strength").innerHTML = elfStr;
document.getElementById("intelligence").innerHTML = elfInt;
document.getElementById("health").innerHTML = elfHlth;
document.getElementById("dexterity").innerHTML = elfDext;
}
var manStats = function(){
var manStr = str + 2;
var manInt = int;
var manHlth = (hlth - 1) * 10;
var manDext = dext;
document.getElementById("strength").innerHTML = manStr;
document.getElementById("intelligence").innerHTML = manInt;
document.getElementById("health").innerHTML = manHlth;
document.getElementById("dexterity").innerHTML = manDext;
}
var dwarfStats = function(){
var dwarfStr = str + 1;
var dwarfInt = int;
var dwarfHlth = (hlth + 1) * 10;
var dwarfDext = dext - 1;
document.getElementById("strength").innerHTML = dwarfStr;
document.getElementById("intelligence").innerHTML = dwarfInt;
document.getElementById("health").innerHTML = dwarfHlth;
document.getElementById("dexterity").innerHTML = dwarfDext;
}
racePrompt is defined inside the nameAndRaceFunction() function scope. It is not accessible outside of it. Further: you lower case it, so later I will check only for race not racePrompt.
One solution would be to make race global like str, int, hlth, dext
var nameAndRaceFunction = function() {
namePrompt = prompt("What shall you name your character?");
var racePrompt = prompt("What race shall your character be? Please spell it correctly, with no capitals.");
race = racePrompt.toLowerCase();
var totalSentence = namePrompt + " the " + race;
document.getElementById("nameAndRace").innerHTML = totalSentence;
getStatFunction()
}
var namePrompt, race;
var str = Math.floor((Math.random() * 10) + 1);
var int = Math.floor((Math.random() * 10) + 1);
var hlth = Math.floor((Math.random() * 10) + 1);
var dext = Math.floor((Math.random() * 10) + 1);
var getStatFunction = function() {
if (race === "elf") {
elfStats();
} else if (race === "dwarf") {
dwarfStats();
} else if (race === "man") {
manStats();
} else {
}
}
getStatFunction should be called with the race as argument or you should define the variable racePrompt outsite the function
Also, if you mean to make a player, a good idea should be have it as an object and use the nameAndRaceFunction like a constructor
I have a function called save with this code, it's meant to save data from a timer.
The class with the Model is this:
var Schema = mongoose.Schema;
var Timer = new Schema({
Time: {type: Number},
Desc: {type: String},
Doc: {type: String}
});
Timer.statics.findByDesc = function(value, callback){
this.find({ Desc: {"$regex": value, "$options": "i"}}, callback);
}
Timer.statics.findByDoc = function(value, callback) {
this.find({ Doc: { "$regex": value, "$options": "i" }}, callback);
}
Timer.statics.findAll = function(callback){
this.find({}, callback);
}
module.exports = mongoose.model('Timer', Timer);
the model is defined by this code which is imported with:
var Timer = require('./../../models/timer');
but I'm testing it with constants in a function which is called by clicking button, this is the code inside the function:
var newTimer = new Timer({
Time: 6000, Desc: "My first timertest!", Doc: "Test's Dossier"
});
newTimer.save();
however with trial and error I have figured out that it never calls newTimer.save(), it seems to get stuck somewhere without ever leaving the var newTimer = new Timer() function.
I have tried my Timer Model code in other files with code like:
/**
* Created by kevin on 08/03/2016.
*/
var Timer = require('../models/timer'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/legalapp');
mongoose.connection.on('open', function() {
console.log('Mongoose connected.');
});
var newTimer = new Timer({
Time: 5000, Desc: "My first timertest!", Doc: "Test's Dossier"
});
console.log(newTimer.Time);
console.log(newTimer.Desc);
console.log(newTimer.Doc);
newTimer.save();
mongoose.connection.close();
and this did work, so after 3 hours of trying, I'm going crazy, so I came here.
I am using javascript, nodeJS, jquery and mongoose in my project.
Here is the entire file:
var timers = [], Timer = require('./../../models/timer');
function timer(id){
this.id = id;
this.running = false;
this.start = new Date();
this.current = new Date();
this.paused = new Date();
this.timed = 0;
this.desc = "";
this.pauseTime = 0;
this.pauseTimeBuffer = 0;
this.prevTimed = 0;
this.first = true;
this.h = Math.floor(this.timed / 1000 / 60 / 60);
this.timed -= this.h * 1000 * 60 * 60;
this.h = checkTime(this.h);
this.m = Math.floor(this.timed / 1000 / 60);
this.timed -= this.m * 1000 * 60;
this.m = checkTime(this.m);
this.s = Math.floor(this.timed / 1000);
this.timed -= this.s * 1000;
this.s = checkTime(this.s);
}
function startTime(timer){
if(!timer.running) {
if (timer.first) {
timer.start = new Date();
timer.first = false;
}
timer.running = true;
time(timer);
}
}
function stopTime(timer){
if(timer.running) {
if (timer.pauseTime === 0) {
timer.paused = new Date();
} else {
timer.paused = new Date();
timer.pauseTimeBuffer = timer.pauseTime;
}
timer.running = false;
time(timer);
}
}
function save(timer){
//stopTime(timer);
/*var desc = prompt("Enter the description of this task", timer.desc);
var dossier = prompt("What dossier does this timer belong to?");
var current = new Date();
var timed = timer.current - timer.start;
timed -= timer.pauseTime;
*/
var newTimer = new Timer();
newTimer.Time = 6000;
newTimer.Desc = "My first timertest!";
newTimer.Doc = "Test's Dossier";
newTimer.save();
alert("yay");
}
function time(timer) {
if(timer.running) {
var name = '#timer' + timer.id;
var $time = $('' + name);
timer.current = new Date();
timer.timed = timer.current - timer.start;
timer.timed -= timer.pauseTime;
timer.h = Math.floor(timer.timed / 1000 / 60 / 60);
timer.timed -= timer.h * 1000 * 60 * 60;
timer.h = checkTime(timer.h);
timer.m = Math.floor(timer.timed / 1000 / 60);
timer.m = checkTime(timer.m);
timer.timed -= timer.m * 1000 * 60;
timer.s = Math.floor(timer.timed / 1000);
timer.timed -= timer.s * 1000;
timer.s = checkTime(timer.s);
$time.html("" + timer.h + ":" + timer.m + ":" + timer.s);
//var t = setTimeout(time(timer), 10);
}else{
timer.current = new Date();
timer.pauseTime = timer.current - timer.paused;
timer.pauseTime += timer.pauseTimeBuffer;
//var t = setTimeout(time(timer), 10);
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function init(timer){
var name = "#timer" + timer.id;
var $time = $('' + name)
$time.html("" + timer.h + ":" + timer.m + ":" + timer.s);
run();
}
function run(){
for(i = 0; i < timers.length;i++){
var timer = timers[i];
setTimeout(time(timer), 10);
}
setTimeout(run, 10);
}
function action(id, action){
if(action === "start"){
var t = timers[id - 1];
startTime(t);
}else if(action === "stop"){
var t = timers[id - 1];
stopTime(t);
}else if(action === "save"){
var t = timers[id - 1];
save(t);
}
}
function stopAll(){
for(i = 0; i < timers.length; i++){
var t = timers[i];
stopTime(t);
}
}
function add(){
stopAll();
var number = timers.length + 1;
var starttext = '"start"';
var savetext = '"save"';
var stoptext = '"stop"';
var newTimer = new timer(number);
timers.push(newTimer);
$('#timers').append("<br/>" +
"<h1>Timer " + number + "</h1>" +
"<div id=" + 'timer' + number + ">Test</div>" +
"<button onclick='action(" + number + ", " + starttext + ")" + "'>Start</button>" +
"<button onclick='action(" + number + ", " + stoptext + ")" + "'>Stop</button>" +
"<button onclick='add()'>Add</button>" +
"<button onclick='action(" + number + ", " + savetext + ")" + "'>Save</button>" +
"<p class='description' id='" + 'desc' + number + "'>Click here to enter a description</p>");
$(".description").click(function(){
var text = prompt("Please enter your description here");
if(text === ""||text === null) {
$(this).html("Click here to enter a description");
}else{
$(this).html(text);
timers[number - 1].desc = text;
}
});
init(newTimer);
setTimeout(startTime(newTimer));
}
Save is the function that I have problems with.
You cannot make client side Javascript and server side Javascript coexist at the same file. Jquery/HTML code runs inside a browser and nodejs/express runs inside a server.
Reference to Client-Server concept
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming
Some good reference to work with NodeJS
calling a server side function from client side(html button onclick) in node.js
Sample app
https://github.com/jmhdez/Nodejs-Sample
I'm trying to get server time at start and update it, cause i've to cotnrol some elements with real time. The problem is that if my serverTime doesn't have T the time is NaN on firefox and IE, but if i replace the empty space with T on chrome and IE i've a wrong time.
I now the work-around of replacing white space with T sucks but im outta of time :)
Thanks everybody
At start:
$tmpTime = date("Y-m-d H:i:s");
Head:
<script>
var serverTime = '<?=$tmpTime?>';
serverTime = serverTime.replace(" ", "T");
</script>
Script:
setInterval(function () {
console.log(serverTime);
var tmpTime = new Date(serverTime);
console.log(tmpTime);
var t = tmpTime.getTime();
t = t + 1000;
tmpTime = new Date(t);
serverTime = t;
if (tmpTime.getMinutes() < 10) {
var minutes = "0" + tmpTime.getMinutes();
} else {
var minutes = tmpTime.getMinutes();
};
newTime = tmpTime.getHours() + ":" + minutes;
$('#liveTime').text(newTime);
if ($("#program li[time-id='" + newTime + "'][class='alert']").length !== 0) {
alert("Lo streaming da te programmato sta per iniziare!");
$("#program li[time-id='" + newTime + "'][class='alert']").removeClass("alert");
}
titleToShow();
}, 1000);
function titleToShow() {
$("#program li").each(function () {
var prevTime = $(this).prev("li").attr("time-id");
var thisTime = $(this).attr("time-id");
var nextTime = $(this).next("li").attr("time-id");
currentTime = Date.parse('01/01/2011 ' + newTime);
prevTime = Date.parse('01/01/2011 ' + prevTime);
nextTime = Date.parse('01/01/2011 ' + nextTime);
thisTimeNew = Date.parse('01/01/2011 ' + thisTime);
if (currentTime >= thisTimeNew && currentTime < nextTime && currentTime > prevTime) {
title = $(this).find("p").text();
if (title != $("p#playingTitle").text()) {
$("p#playingTitle").text(title);
}
}
})
}
Don’t use a formated date, just pass the Unix timestamp value to the script (don’t forget to multiply it by 1000, because JS works with milliseconds).
var serverTime = <?php echo time(); ?>;
var tmpTime = new Date(serverTime * 1000);