Javascript will not update or display the system time< how come? - javascript

This is my javascript code, I checked it in Chrome and its not giving me an error
window.onload = function() {
var timeClock = function (){
setTimeout("timeClock()", 1000);
var timeObj = new Date();
var currTime = timeObj.getHours(); + " : " + timeObj.getMinutes(); + " : " + timeObj.getSeconds();
document.getElementById("#clock-container").innerHTML = "asd";
}
}
I am trying to update this div with the current system time
<div id="clock-container"></div>

You have multiple logic and other mistakes.
You are attempting to register the callback, but your setTimeout is in the callback itself. Move setTimeout("timeClock()", 1000); outside the callback.
Presumably you also want to replace setTimeout with setInterval to have the clock continuously update, and also avoid having to call setTimeout in the callback.
There's also no reason to use a string to call timeClock, so use setInterval(timeClock, 1000); instead and avoid the evil that is code evaluation.
document.getElementById("#clock-container") should be document.getElementById("clock-container").
Your currTime expression has several ; where they don't belong, fix those and you can use this variable instead of your string.
You can also call timeClock immediately after load, to avoid waiting for the first interval.
Working Example:
window.onload = function() {
var timeClock = function (){
var timeObj = new Date();
var currTime = timeObj.getHours() + " : " + timeObj.getMinutes() + " : " + timeObj.getSeconds();
document.getElementById("clock-container").innerHTML = currTime;
}
setInterval(timeClock, 1000);
timeClock();
}
<div id="clock-container"></div>

I am not sure what you're trying to do but The script should be
window.onload = function() {
var timeClock = function (){
var timeObj = new Date();
var currTime = timeObj.getHours() + " : " + timeObj.getMinutes() + " : " + timeObj.getSeconds();
document.getElementById("clock-container").innerHTML = currTime;
setTimeout(timeClock, 1000);
}
timeClock();
}

Related

Why is my .change() function inside jquery plugin is not working?

I am trying to make a simple age calculator. It simply adds the age on the side of the input. It calculates the age that is inside the input by datepicker.
The .split is not very clean but it is just to change date format.
I am guessing my problem is a problem of scope.
What I d like, is my plugin to update the age on change of the input. Here it is:
(function ($) {
$.fn.ageIt = function () {
var that = this;
var positonthat = $(that).position();
var sizethat = $(that).width();
//Add div for ages
var option = {
"position": " relative",
"top": "0",
"left": "300"
};
var templateage = "<div class='whatage" + $(this).attr('id') + "' style='display:inline-block;'>blablabla</div>";
$(that).after(templateage);
var leftposition = (parseInt(sizethat) + parseInt(positonthat.left) + parseInt(option.left));
var toposition = parseInt(positonthat.top) + parseInt(option.top);
$('.whatage' + $(this).attr("id")).css(
{
position: 'absolute',
top: toposition + "px",
left: leftposition + "px",
"z-index": 1000,
}
);
//uptadateage
function updateage(myobj) {
var formateddate = myobj.val().split(/\//);
formateddate = [formateddate[1], formateddate[0], formateddate[2]].join('/');
var birthdate = new Date(formateddate);
var age = calculateAge(birthdate);
$('.whatage' + $(myobj).attr("id")).text(age + " ans");
};
//updateage($(this));
$(this).on("change", updateage($(this)));
//
}
})(jQuery);
function calculateAge(birthday) {
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
$("#BirthDate").ageIt();
This line:
$(this).on("change", updateage($(this)));
means, "Set the handler for the 'change' event to the result of calling the function updateage() with the parameter $(this). That's a function call. Because you've already captured the value of this in the variable that, you can write updateage() such that it doesn't need a parameter:
function updateage() {
var formateddate = that.val().split(/\//);
formateddate = [formateddate[1], formateddate[0], formateddate[2]].join('/');
var birthdate = new Date(formateddate);
var age = calculateAge(birthdate);
$('.whatage' + $(that).attr("id")).text(age + " ans");
};
Then to set up the event handler:
$(this).on("change", updateage);
Note that in a jQuery add-on like you're building, the value of this will be the jQuery object upon which the method is called. You don't need to make a new jQuery object ($(this), $(that)). So it would work to just write:
this.on("change", updateage);

setInterval not working as expected with javascript oops

Js Fiddle : check here
I have setInterval() inside a method of a class. It works properly when single instance is created but fails when many instance created. When more than one instance created , only the last created instance work and other stops.
My script is as below :
function timer() {
this.ran = Math.floor(Math.random() * 100) + 1;
this.cls = this.ran + '_ocar';
this.div = '<div class="' + this.cls + '">' + this.cls + '</div>';
$('body').append(this.div);
this.run = function() {
thi = this;
thi.k = 0;
setInterval(function() {
console.log(thi.cls);
$('.' + thi.cls).html(thi.k++);
}, 1000);
}
}
one = new timer();
one.run();
setInterval(function() {
new timer().run();
}, 5000);
thi = this; is being created in the global namespace, so is being overwritten each time you initialise a new timer().
Change it to var thi = this;.
https://jsfiddle.net/daveSalomon/h5e8LLg3/`
I don't like thi as a var name - it looks like a typo. I usually use _this or _scope.
Try this:
function timer(){
var thi = this;
this.ran = Math.floor(Math.random() * 100) + 1;
this.cls = this.ran+'_ocar';
this.div = '<div class="'+this.cls+'">'+this.cls+'</div>';
$('body').append(this.div);
this.run = function(){
thi.k = 0;
setInterval(function(){
console.log(thi.cls);
$('.'+thi.cls).html(thi.k++);
},1000);
}
}
one = new timer();
one.run();
setInterval(function(){
new timer().run();
},5000)
Your variable thi need to be declared locally and moved.

Variable interval for javascript setInterval based on number of inner loop iterations

I'm trying to automate some actions on a webpage but running into some variable setInterval delay issues. The code pulls a list of elements based on classname and iterates over each one performing an action which dynamically creates new elements on the page, once the elements in collection have been processed the code should re-pull the class elements and iterate over the new collection over and over again.
I want the main delay to be dependant on the number of class elements it pulls from the page and iterates over each time. This code will be run on console in Chrome.
Here was my original working code without a variable delay:
var finishedActions = [];
var actionDelaySec = 5;
var totActionsInLoop;
setInterval( function() {
var pageElementsToActOn = document.getElementsByClassName('classname');
totActions = pageElementsToActOn.length;
for(var i =0; i < pageElementsToActOn.length; i++) {
(function(i){
window.setTimeout(function(){
var actionText = pageElementsToActOn[i].textContent;
if (finishedActions.indexOf(actionText) > -1) {
console.log("already finished action");
} else {
finishedActions.push(actionText);
console.log(actionText);
pageElementsToActOn[i].click();
}
}, i * actionDelaySec * 1000);
}(i));
}
console.log("New Loop");
}, 10000);
My first attempt to just change the 10000 figure to a variable caused a crash due to not being able to change setInterval delays while it's running.
After some research I thought I could recursively nest my function and call itself with a new delay each time.
This code also works but for some reason doesn't change the actual delay each time the main function is called but instead sets the delay to whatever is run on the first iteration:
var finishedActions = [];
var actionDelaySec = 160;
var totActionsInLoop = 5;
var totActionsMade = 0;
var myFunction = function(){
var pageElementsToActOn = document.getElementsByClassName('classname');
totActionsInLoop = pageElementsToActOn.length;
for(var i =0; i < pageElementsToActOn.length; i++) {
(function(i){
window.setTimeout(function(){
var actionText = pageElementsToActOn[i].textContent;
if (finishedActions.indexOf(actionText) > -1) {
console.log("already finished action (" + actionText + ").");
} else {
finishedActions.push(actionText);
console.log(actionText + " Connected At: " + timeStamp());
totActionsMade++;
pageElementsToActOn[i].click();
}
}, i * (actionDelaySec * 1000));
}(i));
}
console.log("New Loop -- Actions on page: " + totActionsInLoop + "-- Total actions finished: " + totActionsMade + " -- Started At: " + timeStamp());
setInterval(myFunction, (totActionsInLoop * (actionDelaySec * 1000)));
};
myFunction();
Can anyone explain to me why the delay isn't changing with each new function call and possibly help me fix the code to work as intended?
Thanks.

How to put a timestamp within a variable name in javascript (e.g. var a12439853 = 1)

I have made a CSS3 ajax loader using this code.
id is the location of the ajaxloader.
This code works fine and the loader functions properly, however if the function is called twice, the Timeout's will cancel each other out because the timeout is assigned to a variable. Somehow, I want to make sure that this will never happen.
Here is the javascript I am using
function ajaxloader(id) {
var i = $("#" + id + " .ajaxpieces").length;
var s = $("#" + id + " .ajaxpieces").filter(function() {
return ($(this).css('background-color') == "rgb(0, 128, 0)");
}).next();
if (s.length < 1) {
s = $("#" + id + " .ajaxpieces").first();
}
s.css('backgroundColor','green').siblings().css('backgroundColor','grey');
ajax_ii = setTimeout(function(){ajaxloader(id);},550);
}
function killloader() {
clearTimeout(ajax_ii);
}
Since every variable are object of window, you can do it this way:
window['a_time'+new Date().getTime()] = setTimeout(function(){
ajaxloader(id);
},550);

how to increment a url with zeros every specific interval "Javascript"?

I want to increment a url automatically using javascript and use it in Greasemonky on "Firefox"
ex:
www.google.com/id=1
www.google.com/id=01
www.google.com/id=001
www.google.com/id=0001
how can I achieve that using javascript???
here is what I wrote
var numberr = “2”;
var totall = “”;
var timeout = 12000;
setTimeout(function() {
var numm = “0” + numberr;
totall = “http://www.google.com/id=0” + numm;
window.location.href = totall;
}, timeout);
but i doesn't increment the zeros as i expected,
can anybody help me?
I don't know what is the problem, maybe it is the Greasemonkey?? I don't know
---------------------------------------------------------------
OK, It seems to be a javascript unfixable problem, So I'll implement the logic in a Windows application using C#, BUT I neet to know how to access [[firefox]] url , and reload action through C# in a windows application, can anybody help?????
Your variable values won't persist between page loads, thus resetting the counter each time. There is a solution, however!
GM_setValue(key, value);
GM_getValue(key[, defaultValue]);
http://diveintogreasemonkey.org/advanced/gm_getvalue.html
Alternatively, you can parse the current URL to determine your location within the loop. Try this:
// ==UserScript==
// #name Incremental URL
// #include http://www.google.com/*
// ==/UserScript==
var url = 'http://www.google.com/id=',
start = '2',
prepend = '0',
limit = 10,
timeout = 1000*12,
regex = new RegExp('^' + url + '(' + prepend + '{0,' + (limit-1) + '})' + start + '$');
matches = window.location.href.match(regex);
if(matches) {
setTimeout(function() {
window.location.href = url + prepend + matches[1] + start;
}, timeout);
}
What number are you coming up with? it looks like you are always going to be adding one more 0 than your description indicates since you are automatically adding one 0 with
var numm = “0” + numberr;
totall = “http://www.google.com/id=0” + numm;
by the look of those lines, even if you start out with "2", your first request will be
www.google.com/id=002
edit: and another thing, you are going to need to assign numm to numberrr at the end of the function call. Is this what you are trying to achieve?
var numberr = “2”;
var totall = “”;
var timeout = 12000;
setTimeout(function() {
var numm = “0” + numberr;
totall = “http://www.google.com/id=” + numm;
window.location.href = totall;
numberr = numm;
}, timeout);
edit again: ya, what Zed says, once you change your page location everything will reset anyways.
try this:
var numberr = “2”;
var totall = “”;
var timeout = 12000;
var numm;
setTimeout(function() {
numm += “0”;
totall = “http://www.google.com/id=0” + numm + numberr;
window.location.href = totall;
}, timeout);
var xcall = function()
{
this.url = "http://www.google.com/id=";
this.count = 0;
this.numberr = '1';
this.timeout = 12000;
};
xcall.prototype.ceros = function() {
var ret = "";
for(var x=0; x<this.count; x++){
ret += "0";
}
this.count++;
return ret;
};
xcall.prototype.sto = function() {
var locat = this.url + this.ceros() + this.numberr;
alert(locat);
//window.location.href = this.url + this.ceros + this.numberr;
};
var calls = new xcall();
setTimeout("calls.sto()", calls.timeout);
setTimeout("calls.sto()", calls.timeout);

Categories