I am building a project to help kids in school learn how to read faster. I have borrowed bits of code here and there and mixed up a timer and text generator.
Now I am trying to build a function to generate a summary of the latest reading time (so that they can see progress), perhaps in the form of <ol>, I guess I need to iterate over an array, push into it and then display but none of that seems to work.
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var ampm = "";
m = checkTime(m);
if (h > 12) {
h = h - 12;
ampm = " PM";
} else if (h == 12) {
h = 12;
ampm = " AM";
} else if (h < 12) {
ampm = " AM";
} else {
ampm = "PM";
};
if (h == 0) {
h = 12;
}
document.getElementById('display').innerHTML = h + ":" + m + ampm;
var t = setTimeout(function() {
startTime()
}, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
function startDate() {
var d = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("date").innerHTML = days[d.getDay()] + " | " + [d.getMonth() + 1] + "/" + d.getDate() + "/" + d.getFullYear();
}
var quotes = ["",
"\"Dude, suckin' at something is the first step at being sorta good at something.\"<br>- Jake <small><em>(Adventure Time)</em></small>",
"\"Either I will find a way, or I will make one.\"<br> - Philip Sidney",
"\"Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.\"<br>- Thomas A. Edison",
"\"You are never too old to set another goal or to dream a new dream.\"<br>- C.S Lewis",
"\"If you can dream it, you can do it.\"<br>- Walt Disney",
"\"Never give up, for that is just the place and time that the tide will turn.\"<br>- Harriet Beecher Stowe",
"\"I know where I'm going and I know the truth, and I don't have to be what you want me to be. I'm free to be what I want.\"<br>- Muhammad Ali",
"\"If you always put limit on everything you do, physical or anything else. It will spread into your work and into your life. There are no limits. There are only plateaus, and you must not stay there, you must go beyond them.\"<br>- Bruce Lee",
];
function genQuote() {
var quote = document.getElementById("quote");
var generate = document.getElementById("gen");
generate.addEventListener("click", changeText);
quote.innerHTML = quotes[0];
function changeText() {
var searchTerm = quote.innerHTML;
var index = quotes.indexOf(searchTerm) + 1;
if (index == quotes.length) index = 0;
var result = quotes[index];
quote.innerHTML = result;
return;
}
}
var startTime, endTime;
function start() {
startTime = performance.now();
};
function end() {
endTime = performance.now();
var timeDiff = endTime - startTime;
timeDiff /= 1000;
var seconds = Math.round(timeDiff);
var minutes = Math.round(seconds / 60);
document.getElementById("quote").innerHTML = ("You have read for:" + " " + minutes + " minutes" + " " + seconds + " seconds");
setTimeout(function() {
location.reload();;
}, 5000);
}
function report() {
// results = [];
// times = document.getElementById("quote").innerHTML;
// for (i=0; i <= times.length; i++) {
// results.push(i);
// return results;
// }
}
<div id="display"></div>
<div id="date"></div>
<div id="quote"></div>
<div id="get"></div>
Here is the HTML in case that help:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<title>2 Cool 4 School</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<body onload="startTime(); startDate()">
<div class="container">
<div id="date"></div>
<div id="display"></div>
<div id="content">
<p id="quote">"the people who are crazy enough to think they can change the world are the ones who do." <br/>- Steve Jobs</p>
</div>
</div>
<div id="b-nav">
<ul>
<button id="genone"class="btn btn-outline-primary" onclick="start()">Start</button>
<button id="gen" onclick="genQuote()">Continue reading</button>
<button id="genthree" class="btn btn-outline-success" onclick="report()">History</button>
<button id="gentwo" class="btn btn-outline-secondary" onclick="end()">End</button>
</ul>
</div>
</body>
<script src="script.js"></script>
</html>
Right now when I click Stars the timer runs, when I click End after that I am provided "you have read for: 0 minutes 4 seconds"
I would like to get a report of this something like:
you have read for: 3 minutes 30 seconds
you have read for: 2 minutes 50 seconds
you have read for: 1 minutes 40 seconds
etc Hope that helps(sorry I didnt get the snippet thing)
the biggest problem is placing "return results;" inside your loop. which means your loop never fully executes. move that outside your loop.
secondly, your report() function is just going to return a string of numbers, [0,1,2,3,4...] which is probably not what you are looking for.
Related
I need to write a function to validate the time of user input from console. The format of the time is HH:mm in 24 hours time.
function isValidTime(timeString) {
var regex_time = /^\d{2}\:\d{2}$/;
if(!regex_time.test(timeString))
{
return false;
}
var hour = timeString.getHour();
var minute = timeString.getMinutes();
if ((hour > 0 && hour <= 23) && (minute > 0 && minute <= 59)) {
return true;
}
}
This is the code I have so far. When I input 5:01, the output is invalid format. When I input 17:01, it shows
node:internal/readline/emitKeypressEvents:71
throw err;
^
TypeError: timeString.getHour is not a function
Could you please help with this function, I am reading user input with readline.
I suggest you use capture groups in the regular expression... And the match method.
Match will return null if no match at all
or an array containing the full match at position 0 followed by all capture group results.
function isValidTime(timeString) {
const regex_time = /^(\d{2})\:(\d{2})$/; // Use capture groups
const timeMatches = timeString.match(regex_time)
if(!timeMatches){
return false
}
const hour = parseInt(timeMatches[1])
const minute = parseInt(timeMatches[2])
return hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59
}
console.log(isValidTime("5:01")) // false
console.log(isValidTime("17:05")) // true
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div>
<input type="text" placeholder="MM" id="month">
<input type="text" placeholder="DD" id="date">
<input type="text" placeholder="YYYY" id="year">
<button>Check</button>
<h1>Result</h1>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="script.js"></script>
</body>
</html>
let btnCheck = document.querySelector('button');
let inputMonth = document.querySelector('#month');
let inputDate = document.querySelector('#date');
let inputYear = document.querySelector('#year');
let result = document.querySelector('h1');
btnCheck.addEventListener('click', (event) => {
let month = inputMonth.value;
let year = inputYear.value;
let date = inputDate.value;
// true in the end, so that our date string and date format should match exactly - in moment js it is called Strict Parsing
result.innerText = moment(`${month}/${date}/${year}`, 'MM/DD/YYYY', true).isValid();
});
Solution :
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var hour = today.getHours (
var minutes = today.getMinutes
Another Tip :
If you Get A Another Error you can write
var today = new Date();
var parag = document.getElementById("date")
var time = today.getHours () + ":" + today.getMinutes () + ":" + today.getSeconds();
parag.innerHTML = time
I have dynamically set two date inputs to pick dates based on current date in the first input(start_date), and based on what is selected in first input for the second input(end_date). The fields seem to update just well when dates are picked, until when the next date has to be in the following year, just when date picker in end_date stops respondig to min atrribute. I am testing my work in chrome browser. Can someone show me how to go around this one? Below is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="toMyStylesheets"/>
<link rel="stylesheet" href="toMyStylesheets"/>
<title>MyTitle</title>
</head>
<body>
<input type="date" name="start_date" id="start_date" />
<input type="date" name="end_date" id="end_date" disabled />
</body>
</html>
And below is my JavaScript:
let startDate = document.getElementById('start_date');
let endDate = document.getElementById('end_date');
// Enable endDate if startDate is filled, as well as set minimum dates
let currentDate = new Date();
let dd = currentDate.getDate();
let mm = currentDate.getMonth()+1; // January is [0] so I added 1 to get the right month.
let yy = currentDate.getFullYear();
let today = yy+'-'+mm+'-'+dd;
$(document).ready(() => {
startDate.setAttribute("min", today);
});
startDate.oninput = () => {
if (startDate.value.length > 0) {
endDate.disabled = false;
let fullSelectedDate = new Date(startDate.value);
fullSelectedDate.setDate(fullSelectedDate.getDate() + 1); // Updating selected day to following day
let selectedDd = fullSelectedDate.getDate();
let selectedMm = fullSelectedDate.getMonth() +1;
let selectedYy = fullSelectedDate.getFullYear();
let nextDay = selectedYy+'-'+selectedMm+'-'+selectedDd;
endDate.setAttribute("min", nextDay);
} else {
endDate.disabled = true;
}
};
Try like this:
$(document).ready(() => {
let startDate = document.getElementById('start_date');
let endDate = document.getElementById('end_date');
// Enable endDate if startDate is filled, as well as set minimum dates
let currentDate = new Date();
let dd = currentDate.getDate();
let mm = currentDate.getMonth() + 1; // January is [0] so I added 1 to get the right month.
let yy = currentDate.getFullYear();
if(dd < 10) {
dd = "0" + dd.toString();
};
if(mm < 10) {
mm = "0" + mm.toString();
};
let today = yy + '-' + mm + '-' + dd;
startDate.setAttribute("min", today);
startDate.oninput = () => {
if (startDate.value.length > 0) {
endDate.disabled = false;
let fullSelectedDate = new Date(startDate.value);
fullSelectedDate.setDate(fullSelectedDate.getDate() + 1); // Updating selected day to following day
let selectedDd = fullSelectedDate.getDate();
let selectedMm = fullSelectedDate.getMonth() + 1;
let selectedYy = fullSelectedDate.getFullYear();
if(selectedDd < 10) {
selectedDd = "0" + selectedDd.toString();
};
if(selectedMm < 10) {
selectedMm = "0" + selectedMm.toString();
};
let nextDay = selectedYy + '-' + selectedMm + '-' + selectedDd;
endDate.setAttribute("min", nextDay);
} else {
endDate.disabled = true;
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="toMyStylesheets"/>
<link rel="stylesheet" href="toMyStylesheets"/>
<title>MyTitle</title>
</head>
<body>
<input type="date" name="start_date" id="start_date" />
<input type="date" name="end_date" id="end_date" disabled />
</body>
</html>
The reason the min attribute on end_date was not working was because it was not strictly in 'YYYY-MM-DD' format. For example, if you set start_date to be 2020-12-31, nextDay has a value of '2021-1-1', which gets ignored in the min attribute. In the code above, a few simple if statements are added to convert the '1' values to '01' so that nextDay becomes '2021-01-01'.
Sorry if this topic is in the "annoying ones category". I recently tried to learn JS and I'm trying to make a simple clock to work. Nothing too fancy I'd say but the problem is that I can't update the values of my hours, minutes and seconds. I used .innerHTLM with a setInterval but it doesn't work. In Chrome's inspector it seems to try changing the datas but no... Any ideas guys ?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style-clock.css">
<title>Clock</title>
</head>
<body>
<div class="container">
<div class="clock">
<span id="hours"></span>
<span id="mins"></span>
<span id="secs"></span>
</div>
</div>
<script src='../js/app-clock.js'></script>
</body>
</html>
JS:
const time = new Date();
function currentTime(){
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime,500);
You were close. Since you define time outside of the interval function, it only gets assigned once. Just move time into the currentTime() function like this:
function currentTime() {
const time = new Date();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime, 500);
<div class="container">
<div class="clock">
<span id="hours"></span>
<span id="mins"></span>
<span id="secs"></span>
</div>
</div>
You have decelerated outside of function that is called intervals.
CodePen Example
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style-clock.css">
<title>Clock</title>
</head>
<body>
<div class="container">
<div class="clock">
<span id="hours"></span>
<span id="mins"></span>
<span id="secs"></span>
</div>
</div>
<script src='../js/app-clock.js'></script>
</body>
</html>
JS
setInterval(function(){
const time = new Date();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}, 500);
The problem seems to be the positioning of the const time.
The thing is, the output of Date() will be set to const time at the beginning of the script and the currentTime() function will keep on updating the same values over and over again. So, in your case, the values were actually getting updated but since they were the same values, you couldn't make the difference.
Solution: To make it work, you need to update the value of the const time every time you need to update the value of the innerHTML. You simply need to do the following change:
JS:
function currentTime(){
const time = new Date();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime,500);
Move the "new Date()" line into the function to set the time each interval to the current time.
function currentTime(){
const time = new Date();
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
document.getElementById("hours").innerHTML = h;
document.getElementById("mins").innerHTML = m;
document.getElementById("secs").innerHTML = s;
}
setInterval(currentTime,500);
Hi there!
I am a beginner both in JavaScript and in Google Sheets, but I am trying to find a way for Google Apps Script to basically scan the data I have brought in there from a Swedish Online Bank where they have some information about how the stocks go up and down.
Furthermore, I want to be notified by email when one of these on my list goes down by for example 5 % in a day.
I tried something like this:
let arrayRow = ["+" + 5.91 + "%", "+" + 5.22 + "%", "-" + 5.5 + "%"];
console.log(arrayRow);
function stockPricePlus() {
if (arrayRow >= "+" + 5 + "%") {
console.log("Yay! One of your stocks are going up by 5 % or more!");
}
}
function stockPriceMinus() {
if (arrayRow <= "-" + 5 + "%") {
console.log("Oh noes! One of your stocks are going down by 5 % or more!");
}
}
stockPricePlus();
stockPriceMinus();
And this works in my JavaScript file, but I am not quite sure how to make it pull the data continuously from the Google Sheets and run through them like a loop?
I found something on the internet that seemed to kind of do the job, but I also see that there are some missing parts in the code.
function sendEmails () {
var sheet = SpreadsheetApp.getActiveSheet();
var Price = sheet.getRange("B34:B").getValues();
var data = Price.getValues();
var results = [];
for (var i = 0; i < data.length; ++i) {
var row = data[i];
Logger.log(Price);
if (Price >= "+" + 5 + "%") {
MailApp.sendEmail("johnsmith#gmail.com", "Stock Price Alert from Stock Price Google Script", "One of your stocks are going up by 5 % or more!");
}
if (Price <= "-" + 5 + "%") {
MailApp.sendEmail("johnsmith#gmail.com", "Stock Price Alert from Stock Price Google Script", "One of your stocks are going down by 5 % or more!");
}
A ClientSide Timer for Collecting Periodic Stock Prices using GoogleFinance cell formulas
This code is a portion of code that I have used to check stocks. It has a timer function which runs clientside on your browser and you can adjust the sampling rate as you desire. I'd recommend no less that once every 5 minutes. That gives a good long time to get everything done. I also added a checkStats function which calculates percent change using the formula (max-min/max) * 100 and it compares this value with a value that you can set for each stock on the StockPrices page. It is also set up to send emails if the percent change is greater than a threshold and you can set. You can have as many stocks as you wish but you may need to adjust the sample rate if you try to get too many. You will have to add the email recipient address.
I have several other functions which chart the various stocks in different ways that I didn't include in this. I tried to keep this simple so I wouldn't be surprised if I have inadvently left some things out. Please note this script does not start automatically each day. In fact I hardly ever use it but I thought it would be an interesting thing to do and since then I've found the timer portion to be quite handy.
It's been my experience that GoogleFinance tags do not refresh regularly throughout the day. I've seen them not change at all for as long as 12 minutes while watching the stock prices change on another more elaborate system that runs on a personal computer.
datatimer.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<style>
#my_block{border:2px solid black;background-color:rgba(0,150,255,0.2);padding:10px 10px 10px 10px;}
#conv_block{border: 1px solid black;padding:10px 10px 10px 10px;}
.bttn_block{padding:5px 5px 0px 0px;}
.sndr_block {border:1px solid rgba(0,150,0,0.5);background-color:rgba(150,150,0,0.2);margin-bottom:2px;}
</style>
</head>
<body>
<form>
<div id="my_block" class="block form-group">
<div class="sndr_block">
<div id="myClock" style="font-size:20px;font-weight:bold;"></div>
<br />Timer Duration(minutes):
<br /><input id="txt1" type="text" size="4" class="action"/>
<select id="sel1" onChange="loadTxt('sel1','txt1');">
</select>
<div id="cntdiv"></div>
<br /><strong>Timer Controls</strong>
<div class="bttn_block"><input type="button" value="Start" name="startShow" id="startShow" onClick="startmytimer();changeData();" class="red" /></div>
<div class="bttn_block"><input type="button" value="Stop" name="stopTimer" id="stopTimer" class="red" /></div>
<div class="bttn_block"><input type="button" value="Single Ping" name="changedata" id="chgData" class="red" onClick="changeData();" /></div>
</div>
<div id="btn-bar">
<br /><input type="button" value="Exit" onClick="google.script.host.close();" class="green" />
</div>
</div>
</form>
<script>
var idx=1;
var myInterval='';
var cnt=0;
$(function() {
var select = document.getElementById('sel1');
select.options.length = 0;
for(var i=1;i<61;i++)
{
select.options[i-1] = new Option(i,i * 60000);
}
select.selectedIndex=4;
$('#startTimer').click(startmytimer);
$('#stopTimer').click(stopTimer);
$('#txt1').val(String(select.options[select.selectedIndex].value));
startTime();
});
function startTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('myClock').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i){
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function startmytimer(){
document.getElementById('cntdiv').innerHTML='<strong>Timer Started:</strong> ' + document.getElementById('myClock').innerHTML;
myInterval=setInterval(changeData, Number($('#txt1').val()));
}
function stopTimer(){
document.getElementById('cntdiv').innerHTML='Timer Stopped';
clearInterval(myInterval);
}
function loadTxt(from,to){
document.getElementById(to).value = document.getElementById(from).value;
}
function changeData(){
$('#txt1').css('background','#ffffcc');
google.script.run
.withSuccessHandler(updateDisplay)
.changeData();
}
function updateDisplay(t){
$('#txt1').css('background','#ffffff');
document.getElementById('cntdiv').innerHTML='<strong>Timer Running:</strong> Count= ' + ++cnt + ' <strong>Time:</strong> ' + t;
}
console.log('My Code');
</script>
</body>
</html>
Code.gs:
function onOpen(){
SpreadsheetApp.getUi().createMenu('MyTools')
.addItem('Show Timer SideBar', 'showTimerSideBar')
.addToUi();
}
//This is the function driven by the clientside timer trigger It also creates new data sheets for each day.
function changeData(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('StockPrices');
var rg=sh.getRange(3,1,1,sh.getLastColumn());
var vA=rg.getValues();
var n=new Date();
var tmr=Utilities.formatDate(n, Session.getScriptTimeZone(), "HH:mm:ss");
var ts=Utilities.formatDate(n, Session.getScriptTimeZone(), "E-MMddyy-HHmmss");
var sheetTitle=Utilities.formatDate(n, Session.getScriptTimeZone(), "E-MMddyy");
vA[0][0]=ts;
if(isSheet(sheetTitle)){
ss.getSheetByName(sheetTitle).appendRow(vA[0]);
}else{
var sht=ss.insertSheet(sheetTitle);
var hA=sh.getRange(1,1,1,sh.getLastColumn()).getValues();
hA[0][0]="TimeStamp";
sht.appendRow(hA[0]);
sht.appendRow(vA[0]);
}
checkStats(sheetTitle);
return tmr;
}
function showTimerSideBar()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('StockPrices');
sh.getRange(5,2,1,sh.getLastColumn()-1).clearContent();//clears the sent row
var ui=HtmlService.createHtmlOutputFromFile('datatimer').setTitle('Javascript Trigger Generator');
SpreadsheetApp.getUi().showSidebar(ui);
}
function isSheet(sheetname){
var r=false;
var ss=SpreadsheetApp.getActive();
var allSheets=ss.getSheets();
for(var i=0;i<allSheets.length;i++){
if(allSheets[i].getName()==sheetname){
r=true;
break;
}
}
return r;
}
//This function checks stats and compares them to limits to determine if warning email messages should be sent
function checkStats(page) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(page);
var rg=sh.getRange(1,2,sh.getLastRow(),sh.getLastColumn()-1);
var vA=rg.getValues();
var minA=vA[1].slice(0);
var maxA=vA[1].slice(0);
var pchA=[];
for(var i=2;i<vA.length;i++) {
for(var j=0;j<vA[i].length;j++) {
if(vA[i][j]>maxA[j]) {
maxA[j]=vA[i][j];
}
if(vA[i][j]<minA[j]) {
minA[j]=vA[i][j];
}
}
}
for(var i=0;i<minA.length;i++) {
pchA.push(Number(((maxA[i]-minA[i])/maxA[i]) * 100).toFixed(2));
}
var spsh=ss.getSheetByName('StockPrices');
var limitA=spsh.getRange(4,2,1,spsh.getLastColumn()-1).getValues();
var nameA=spsh.getRange(1,2,1,spsh.getLastColumn()-1).getValues();
var sentA=spsh.getRange(5,2,1,spsh.getLastColumn()-1).getValues();
var msgA=[];
for(var i=0;i<pchA.length;i++) {
if(pchA[i]>limitA[i] && sentA[i]!="SENT") {
msgA.push({name:nameA[i],change:pchA[i],limit:limitA[i],index:i});
}
}
if(msgA.length>0){
var html="<h1>Stocks Exceeding Change Limit</h1>";
var text='Stocks Exceeding Change Limit\n';
for(var i=0;i<msgA.length;i++) {
html+=Utilities.formatString('<br />Stock Name: <strong>%s</strong><br />Limit: <strong>%s</strong><br />Change: <strong>%s</strong><hr width="100%"/><br />', msgA[i].name,msgA[i].limit,msgA[i].change);
text+=Utilities.formatString('\nStock Name: %s\nLimit: %s\nChange: %s\n\n', msgA[i].name,msgA[i].limit,msgA[i].change);
sentA[msgA[i].index]="SENT";
}
//GmailApp.sendEmail(recipient, 'Stocks Exceeding Change Limit', text, {htmlBody:html})
spsh.getRange(5,2,1,spsh.getLastColumn()-1).setValues(sentA);
}
}
This is what the Stock Prices page looks like:
This is what a daily data page looks like:
And this is what the timer sidebar looks like:
Apps Script Documentation
I have currently created a countdown timer using javascript. I want to display a message right after the countdown finishes. So, how do I display that text message if the countdown finishes?
$(function(){
var note = $('#note'),
ts = new Date(2012, 0, 1),
newYear = true;
if((new Date()) > ts){
// The new year is here! Count towards something else.
// Notice the *1000 at the end - time must be in milliseconds
ts = (new Date()).getTime() + 24*60*60*1000;
newYear = false;
}
$('#countdown').countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds){
var message = "";
message += hours + " jam ";
message += minutes + " minit" + " dan ";
message += seconds + " saat" + " lagi!";
note.html(message);
}
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- Our CSS stylesheet file -->
<link rel="stylesheet" href="assets/css/styles.css" />
<link rel="stylesheet" href="assets/countdown/jquery.countdown.css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="continer">
<p><span id="timer"></span></p>
</div>
<center><img class="title" src="title.svg"></center>
<img class="icon1" src="icon1.svg">
<img class="icon2" src="icon2.svg">
<div id="countdown"></div>
<p id="note"></p>
<!-- JavaScript includes -->
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="assets/countdown/jquery.countdown.js"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
Below is the code that I used
Well you can use setInterval, clearInterval and use a counter to keep track of seconds passed
function myFunction() {
var seconds = 0;
var finiteNumber = 300; // any number which can be calculated
var interval = setInterval(function(){
seconds++;
if(seconds === finiteNumber) {
console.log(seconds);
clearInterval(interval )
}
}, 1000);
}
You should use setTimeout as it will automatically stop on one successful execution.
function myFunction() {
var myTimeInSeconds = 600;
setTimeout(function(){
console.log(seconds);
alert('Success');
document.getElementById("demo").innerHTML = "Success Message!";
}, myTimeInSeconds);
}