javascript setTimeout error - javascript

I'm trying to make a progress bar that moves each 5 seconds.
Here is my code:
function Progress(runner, validlinks)
{
if (runner <= validlinks)
{
var myString = document.getElementById('links').value;
var mySplit = myString.split("\n");
var ValidLinksCount = 0;
for(i = 0; i < mySplit.length; i++)
{
if (mySplit[i].search("who") != -1)
ValidLinksCount++;
ValidLinksCount++;
else if (mySplit[i].search("we") != -1)
ValidLinksCount++;
}
var jump = Math.ceil(100 / ValidLinksCount);
runner++;
document.getElementById("progressDiv").style.width = parseInt(document.getElementById("progressDiv").style.width) + jump + "%";
window.setTimeout(Progress(runner,ValidLinksCount), 5000);
}
}
I call it on button submit like this:
<input type="submit" name="submit" disabled="true" onclick="Progress(0,0);" value="check" />
It just runs and doesn't wait 5 seconds until next run, why? Thanks.

Pass, don't call, a function.
window.setTimeout(function() {
Progress(runner,ValidLinksCount);
}, 5000);

Related

Web page displays and animated times table

Hi everyone I am currently stuck trying to debug my program. MY goal is for whenever the button "Start Animation" is clicked, the web page displays an animated times table according to the number that the user enters in the text field in the following manner. For example, if the user entered the number 6 in the text field, then the animation displays 1 x 6 = 6, one second later it replaces it with 2 x 6 = 12, one second later it replaces it with 3 x 6 = 18, etc. If it is 9 x 6 = 54, then one second later it becomes 1 x 6 = 6, and then 2 x 6 = 12, and so on.
var counter;
var animationOn = false;
var counterAnimation;
function updateAnimation() {
var value = document.getElementById('value1').value;
for (var i = 1; i < 1000; i++) {
for (var j = 1; j < 10; j++) {
var product = j * value;
var counterSpan = document.getElementById("counterHolder");
counterSpan.innerHTML = product;
}
}
counterAnimation = setTimeout(updateAnimation, 1000);
}
function startAnimation() {
if (animationOn == false) {
animationOn = true;
counter = 1;
counterAnimation = setTimeout(updateAnimation, 1000);
}
}
function stopAnimation() {
if (animationOn == true) {
animationOn = false;
clearTimeout(updateAnimation);
}
}
<body>
<button onclick="startAnimation();">
Start animation
</button>
<button onclick="stopAnimation();">
Stop animation
</button><br><br>
<label>Enter an integer: </label>
<input type="number" size=20 id=value1 name="value">
<span id="counterHolder">0</span>
</body>
Edited
Here is a complete solution which makes changes displayed value by time
let counter;
let animationOn = false;
let counterAnimation;
let mult = 1;
function updateAnimation() {
let value = document.getElementById('value1').value;
let counterSpan = document.getElementById("counterHolder");
if (mult >= 10) {
mult = 1;
counter = null;
animationOn = false;
counterAnimation = null;
counterSpan.innerHTML = 0;
return;
}
let product = mult * value;
counterSpan.innerHTML = product;
mult++
counterAnimation = setTimeout(updateAnimation, 1000)
}
function startAnimation() {
if (!animationOn)
{
animationOn = true;
counter = 1;
counterAnimation = setTimeout(updateAnimation, 1000);
}
}
function stopAnimation() {
if (animationOn)
{
animationOn = false;
clearTimeout(counterAnimation);
mult = 1
counter = null
animationOn = false
counterAnimation = null
}
}
<body>
<button onclick="startAnimation();">
Start animation
</button>
<button onclick="stopAnimation();">
Stop animation
</button><br><br>
<label>Enter an integer: </label>
<input type="number" size=20 id=value1 name="value">
<span id="counterHolder">0</span>
</body>

multiple alarm clock in javascript using dynamic generated input elements in javascript

I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var room = 0;
var i = 0;
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = document.getElementById('');
var minute = document.getElementById('');
var date = document.getElementById('');
}
</script>
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).
This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.
For an alarm project, I would recommend an interval of one second.
Example (not tested):
JavaScript
var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.
var ONE_SECOND = 1000; // miliseconds
var alarmClock = setInterval(function() {
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}, ONE_SECOND);
To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.
In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.
Hope this helps and good luck!
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.
EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var alarms = {};
var room = 0;
var i = 0;
setInterval(function() {
var current = new Date();
for (var nr in alarms) {
var alarm = alarms[nr];
console.log("checking alarm " + nr + " (" + alarm + ")");
if(current.getHours() == alarm.getHours()
&& current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
alert("ALERT\n"+alarm);
} else{
console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
}
}
}, 60000);
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
console.log(hour + ':' + minute + ' on ' + date);
var dateObj = new Date(date);
dateObj.setMinutes(minute);
dateObj.setHours(hour);
console.log(dateObj);
alarms[values] = dateObj;
}
</script>
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:
<script type="text/javascript">
var snd = new Audio("clock.mp3"); // buffers automatically when created
// Get
if (localStorage.getItem("test")) {
data = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
data = [];
}
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//since page reloads then we will just check it first for the data
function check() {
//current system values
console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
localStorage["test"] = JSON.stringify(data);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
{
check();
}
}
console.log(data);
var room = 1;
//var data = [];
var i = 0;
function GetDynamicTextBox(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var d = date.getDay();
return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
room++;
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
//get the current time and date
var today = new Date();
//current system values
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//first check that whether a same date present in the array or not then push it
var found = -1;
for(var i = 0; i < data.length; i++) {
if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
found = 0;
break;
}
}
//if value does not present then push it into the array
if(found == -1)
{
data.push({hours: hour, minutes: minute, dates: date});
//storing it into localstorage
localStorage.setItem("test", JSON.stringify(data));
}
else
{
alert("Same value Exists");
}
//console.log(data);
function check() {
//current system values
//console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
{
check();
}
}
}
</script>

Timer not accurate [duplicate]

This question already has answers here:
How to create an accurate timer in javascript?
(15 answers)
Closed 6 years ago.
I am building an activity timer, but the code I have is not working properly. The timer is going ~40% faster than real time. What's going wrong?
var sec = 00;
var min = 00;
var hr = 00;
var t;
var timer_is_on = 0;
function timedCount() {
if (min == 0) {
min = 1;
}
document.getElementById('seconds').value = sec;
document.getElementById('minutes').value = min;
$('.node-form .form-item:nth-child(4) input').val(min);
document.getElementById('hours').value = hr;
$('.node-form .form-item:nth-child(3) input').val(hr);
sec = sec + 1;
if (sec == 60) {
sec = 0;
min = min + 1;
if (min == 60) {
min = 1;
hr = hr + 1;
}
}
t = setTimeout("timedCount()", 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetCount() {
stopCount();
sec = 0;
min = 0;
hr = 0;
document.getElementById('hours').value = 00;
$('.node-form .form-item:nth-child(3) input').val('0');
document.getElementById('minutes').value = 00;
$('.node-form .form-item:nth-child(4) input').val('0');
document.getElementById('seconds').value = 00;
}
function putInTimelog() {
// Put hours
var hourItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-hours-0-value-", 0) === 0) {
hourItems.push(hourFields[i]);
}
}
var hourField = 'edit-field-timelog-hours-0-value-';
hourField = hourField.concat(hourItems.length);
document.getElementById(hourField).value = hr;
// Put minutes
var minuteItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-minutes-0-value-", 0) === 0) {
minuteItems.push(hourFields[i]);
}
}
var minuteField = 'edit-field-timelog-minutes-0-value-';
minuteField = minuteField.concat(minuteItems.length);
alert(minuteField);
alert((minuteField).length);
document.getElementById(minuteField).value = min;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span class="timer-title"><strong>Activity timer</strong></span>h:
<input id="hours" readonly="readonly" size="2" type="text" /> m:
<input id="minutes" readonly="readonly" size="2" type="text" /> s:
<input id="seconds" readonly="readonly" size="2" type="text" /><span class="timer-buttons"><input onclick="doTimer()" type="button" value="Start" /> <input onclick="stopCount()" type="button" value="Stop" /> <input onclick="resetCount()" type="button" value="Reset" /> </span>
</form>
View on JSFiddle
clock.js is my repo that might help when used in conjunction with window.setInterval(). Working example included.
Add <script src="https://rack.pub/clock.min.js"></script> to your HTML then call clock.now --> 1462248501241 each time you want a time snapshot. You can add and subtract intuitively from there.
The actual js looks like:
var clock = (function() {
// object to expose as public properties and methods such as clock.now
var pub = {};
//clock.now
Object.defineProperty(pub, "now", {
get: function () {
return Date.now();
}
});
//API
return pub;
}());
var doc = document;
var el = doc.getElementById('output');
window.setInterval(function(){
/// call your function here
el.innerHTML = clock.what.time(clock.now);
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rack.pub/clock.min.js"></script>
<h2 id='output'></h2>

Page refreshes after javascript function

After I excecute my JS function over onClick button method. My site refreshes and everything that was writen with innerHTML is erased. I think i'm missing something. I will just put the whole JS function here. I probably don't understand something and that's what is causing it.
function stisk() {
var stevilo = prompt("Vnesi iskano stevilo");
var seznam = document.getElementById("vnos").value;
var pattern = new RegExp("^[0-9](,\s*[0-9])+$");
var vsota = 0;
var seznam = seznam.split(',');
var dolzina = seznam.length;
var pravilnost = pattern.test(seznam);
if (pravilnost == true) {
for (i = 0; i < dolzina; i++) {
vsota = vsota + parseInt(seznam[i]);
}
for (i = 0; i < dolzina - 1; i++) {
var star = document.getElementById("stevila").innerHTML;
if (isNaN(seznam[i]) == false) {
var starejsi = document.getElementById("stevila").innerHTML = star + parseInt(seznam[i]) + "+";
} else {
document.getElementById("stevila").innerHTML = "Vnos ni pravilen";
}
}
document.getElementById("stevila").innerHTML = starejsi + seznam[dolzina - 1] + "=" + vsota;
var c = 0;
for (i = 0; i < seznam.length; i++) {
if (stevilo == seznam[i]) {
c++;
}
}
if (c == 0) {
alert("stevila ni na seznamu");
} else {
alert("Stevilo je na seznamu");
}
} else {
document.getElementById("stevila").innerHTML = "Napacen vnos stevil";
}
}
HTML:
Here is the browser view:
After i press "V redu" (OK) Everything goes back to the start, expacting me to write a number inside. I want the 2+3+4=9 to stay there if that is possible? Thanks
Change:
<button onclick="stisk()">OK</button>
to:
<input type="button" onclick="stisk()">OK</input>
Like #Teemu said, < button > will submit a form element.
Another solution
<button onclick="stisk(event)">OK</button>
and in javascript
function stisk(e){
e.preventDefault();
...
This can be useful in other cases, like default behavior of <a href element is to redirect page, so you can prevent default behavior with event.preventDefault()
even better solution - let your button submit form, but prevent default on form submit
<form onsubmit="stisk(e)">
...
<button type="submit">
and in javascript
function stisk(e){
e.preventDefault();
...
and it will work when submitting form with Enter in input field.

how to stop a message from a javascript timer from repeating?

I have a timer for my game, but the message will keep going on the mage, so it says it multiple times, i was wondering how you can get it to say it once.
<head>
<script type="text/javascript">
var c=10;
var t;
var timer_is_on=0;
function timedCount() {
document.getElementById('txt').value = c;
c = c - 1;
if (c == -1||c < -1){
var _message = document.createTextNode("You have mined 1 iron ore!");
document.getElementById('message').appendChild(_message);
startover();
}
}
function startover() {
c = 10;
clearTimeout(t);
timer_is_on=0;
doMining();
}
function doMining() {
if (!timer_is_on) {
timer_is_on = true;
t = setInterval(function () {
timedCount();
}, 1000);
}
}
</script>
<SPAN STYLE="float:left">
<form>
<input type="button" value="Mining" onClick="doMining()">
<input type="text" id="txt">
</form>
</SPAN>
<html>
<center>
<div id='message'></div>
Instead of setInterval use window.setTimeout.
This will trigger the function only once.
Edit: if you mean you want one message to appear and update every time, first add global counter:
var mineCount = 0;
Then change the code to this:
if (c <= -1) {
mineCount++;
var _message = "You have mined " + mineCount + " iron ore" + ((mineCount > 1) ? "s" : "") + "!";
document.getElementById('message').innerHTML = _message;
startover();
}
This will assign the contents of the element instead of adding to it each time.
Your startOver function calls doMining(). Surely, it shouldn't...?

Categories

Resources