I'm having a strange issue with javascript : when stocking a new Date().getTime() in a certain variable, it goes to 0.
console.log(new Date().getTime()); // Shows the timestamp
p.channels[p.chann].startTime = new Date().getTime();
console.log(p.channels[p.chann].startTime); // Shows 0
The variable p.channels[p.chann].startTime totally exists (and would otherwise show an error anyway...)
Does anyone know where this problem could come from ? Oo
The problem was that, my variable being an Audio element, I could create the startTime value in it, but it was set to 0 and couldn't be set to anything else.
I have a created a JS Fiddle to show that this works.
p = {};
p.channels = [];
p.chann = 0;
p.channels[p.chann] = {};
p.channels[p.chann].startTime = new Date().getTime();
document.write(p.channels[p.chann].startTime);
The likely reasons for this failing would be that p.chann has been changed between setting and extracting the value, or p.channels[p.chann] hasn't been set as an object (you can test this by commenting out the line where p.channels[p.chann] = {};.
Since this code works, the only issue could be the existance of p.channels[p.chann].startTime while you're retrieving the value, or maybe in your real code you're reading a different value (maybe p.chann changes meanwhile because you're in a loop or you created a closure... it's hard to tell)
var p = {
chann : 0,
channels : [
{ startTime : 0 }
]
};
p.channels[p.chann].startTime = new Date().getTime();
console.log(p.channels[p.chann].startTime); // Shows the value
Related
I'm trying to clear all local storage when the user either completes the game loop or starts a new game, but also keep some values.
I can do this already with my sound values for volume:
// inside a conditional statement that fires when the user chooses to start a new game.
if (newGameBool === '1') {
var tst = myAu;
//myAu is the stored value that the user sets as sound using a range type input
localStorage.clear();
localStorage.setItem("Au", tst);//A newly cleared localStorage just got a new value, and it's the same as it was before.
UI.myLoad();//reload the function that uses LS to do things.
}
How do I do this for key's that have an iterating number attached to them?
Here is how I save them:
var i = +v + +1;
localStorage.setItem("v", i);
var vv = localStorage.getItem("v");
localStorage.setItem("LdrBrd_" + vv, JSON.stringify(LdrBrd));//saves all data with the iterating key name.
Calling them the way i did the sound function:
var gv = v + 1;//v calls the value from LS and adjusted for off-by-one error. gv is a local variable.
if (newGameBool === '1') {
var ldd, vg;
for (var ii = 0; ii < gv; ii++) {
var ld = localStorage.getItem("LdrBrd_" + ii);
if (ld != null) {
//these are the values that i want to pass beyond the clear point
ldd = JSON.parse(ld);//JSON string of data saved
vg = ii;//how many of them.
}
}
localStorage.clear();
for (var xx = 0; xx < vg; xx++) {
var nld = localStorage.getItem("LdrBrd_" + xx);
if (nld != null) {
localStorage.setItem("LdrBrd_" + ii, JSON.stringify(ldd));
}
}
localStorage.setItem("v", vg);
UI.myLoad();
}
I have been using console.log() in various spots to see what is going on. I comment-out the clear function just to see if the values were wrong and they don't save all all. I tried to make a fiddle, but the local storage wasn't working at all there. In visual studio, it works fine but the script to this file is almost 2000 lines long, so i tried to dress it up the best i knew how.
Thanks in advance for any help or guidance.
I was stuck on this for a few days, but i think i found something that will work, so i'll answer my own question in case there is value in posterity.
locatStorage.clear();
/* ^LS clear() function is above all new setItem codes, some variables are declared globally and some are declared at the top of the functional scope or as param^ */
var itemClass = document.querySelectorAll(".itemClass");//the strings are here
if (itemClass) {//make sure some exist
for (var p = 0; p < itemClass.length; p++) {//count them
mdd = JSON.parse(itemClass[p].innerText);//parse the data for saving
localStorage.setItem("v", v);//this is the LS item that saves the amount of items i have, it's declared at the top of the functions timeline.
localStorage.setItem("LdrBrd_" + p, JSON.stringify(mdd));//this setItem function will repeat and increment with 'p' and assign the right string back to the key name it had before.
}
}
The key is to keep the strings physically attached to an element, then call the class name. The i ran a loop counting them. 'mdd' will spit back each item i want. So then all that is left to do is re-set the item back to it's original status.
This has allowed me to create a way for my users to collect trophies and keep them even after clearing the localStorage when the he/she decides to start a new game.
I use CSS to hide the text from the string.
color:transparent;
In my gameLoop, i have a function that will read the saved strings and show them as cards just below the hidden strings.
Since you want to keep some values I recommend one of two things:
Don't call localStorage.clear() and instead only wipe out the values that you want using localStorage.removeItem('itemName'). Since you said the item names have a numeric component, maybe you can do this in a loop to reduce code.
Pull item(s) that you want saved first and restore them after calling clear(). This option is best if there are way more items that you want removed rather than saved (see below)
function mostlyClear() {
var saveMe = {};
saveMe['value1'] = localStorage.getItem('value1');
saveMe['anotherValue'] = localStorage.getItem('anotherValue');
localStorage.clear();
for(var prop in saveMe) {
if(!saveMe.hasOwnProperty(prop)) continue;
localStorage.setItem(prop, saveMe[prop]);
}
}
I was trying to crawl a very old website for a specific tag, I need to get it by it's for= attribute. So I used this piece of code.
var character = document.querySelectorAll("label[for=char_1]");
For some reason it returns an undefined, but I was using this script for a few days now and it worked like a charm. Here's the fun part. Typing that command in browsers console will result in undefined. But typing this alone:
document.querySelectorAll("label[for=char_1]");
Will return a proper NodeList. Why it won't assign to a variable...?
edit: It seems that deleting var and typing character without it will make it work. It's resolved but I would still love to get an answer to "why is this happening"?
edit2:
for (var i = 0; i < 15; i++) {
var character = document.querySelectorAll("label[for=char_" + i +"]");
console.log(character); // this will return [] from the script.
var color = character[0].children[0].style.color;
}
A simple for loop. All I get is Cannot read property 'children' of undefined. But I can type in the very same command document.querySelectorAll... and it will work in the browser and will return NodeList.
I had it working like this in a very hacky script. It worked.
var character1 = document.querySelectorAll("label[for=char_1]");
var characterColor1 = character1[0].children[0].style.color;
edit3:
var character1 = document.querySelectorAll("label[for=char_1]");
var characterColor1 = character1[0].children[0].style.color;
var character2 = document.querySelectorAll("label[for=char_2]");
var characterColor2 = character2[0].children[0].style.color;
// ...
The above code works without a single problem though. I don't think it's DOM not being ready as this code is also run from Greasemonkey script and it works. The only difference is the for loop.
var x = ""; // returns undefined, because it's a var assignment.
var elements = document.querySelectorAll('div');
That's expected behavior when pasted into the console.
edit: It seems that deleting var and typing character without it will make it work. It's resolved
I'm afraid you're creating a global scope variable now. or perhaps characters is an already defined variable in that scope.
Buhah, as I said in edit 3 "the only difference is the for loop". I was so busy trying to find an answer in the DOM-related things that I made the simplest mistake ever done in programming.
See?
char_1
With...
for(var i = 0...)
0! And I was testing char_1 in the browser instead of char_0. Which - truly - returns [] instead of something useful. Time to go on a holiday break I guess, my brain seems to be there already. :)
How to get Time with Cookies javascript When I close the tab or Page?
i'm try use window.onunload but time can not be stored in cookies..
in this code i'm push my cookies to be array
setCookie("time",time,1)
window.onunload =function (){
var set = getCookie('time');
var arr = [];
var push = arr.push(set);
console.log (arr);
return arr;
}
In JavaScript, there is a class called "Date" that let's you get the current time.
var d = new Date(); creates a new Date object and assigns it to the variable d
Now, you have the date and time - you can do whatever you like.
For example: document.getElementById('foo').innerHTML = d.toString() finds the element with the ID of "foo" and sets it's contents to the date and time.
Keep in mind that this date and time display will not constantly update itself. You will have to do that with some timed recursion.
There are many more things you can do with dates. Remember, Google is your friend - look up some things about the Date object.
I am using a JS library for facetracking/emotion detection called CLMtracker.
http://auduno.github.io/clmtrackr/examples/clm_emotiondetection.html
Note: Seems to work best in chrome for those trying to use it.
Is the example I am using, I am wondering how I can access the values for each emotion. For instance, I want check every 10 seconds what the values are and print to console. From this I would also like to compare the values to find the highest and find the emotion that is attached to that. I think I am right in saying that the max() function will give me the highest out of an array?
What I have tried:
I have tried to get emotionData[0].emotion and emotionData[0].value which should print Angry and the value, but it only prints 0. I have also tried the same method with data which does not seem to return anything.
EDIT
emotionData gets me:
however it does not seem to show any update/change as I make my expression change
ec.meanPredict(ctrack.getCurrentParameters()) returns an object containing all the current scores for all emotions.
To get the current score of "Angry", for example, you would do :
ec.meanPredict(ctrack.getCurrentParameters())[0].value
So, in order to get the current most probable emotion, you could do this :
function getCurrentEmotion()
{
if(!ec.meanPredict(ctrack.getCurrentParameters())){setTimeout(getCurrentEmotion,1000);return;}
var currentData = ec.meanPredict(ctrack.getCurrentParameters());
var currentScores = [];
//Gather all scores in an array
for(var i=0;i<currentData.length;i++)
{
currentScores.push(currentData[i].value);
}
//Get the biggest score
var max = Math.max.apply(null,currentScores);
//Calculate its index
var indexOfScore = currentScores.indexOf(max);
//Get the associated emotion
var emotion = currentData[indexOfScore].emotion;
console.log(emotion);
//Set up a loop (did not add 'var', to allow stopping it from outside)
currentEmotionLoop = setTimeout(getCurrentEmotion,3000);
}
To stop the loop at any time, do this :
clearTimeout(currentEmotionLoop);
By the way, the ec variable is declared privately, so in order for this to work, either remove var where it is declared :
var ec = new emotionClassifier();
or write this code in the same file, under the same scope.
I'm working on a website with Jquery tabs dynamically generated. Each tab has an ID.
For the purpose of my script I need to know how many times the user has clicked in a tab.
To record the number of clicks I was thinking of doing an array like this:
var i = new Array(my_tab_id);
(...)
i[my_tab_id] = 0;
Where my_tab_id dynamically changes depending on the tab we're in. Sadly, it doesn't seem like the value of my_tab_id is translated into the array. I don't have i[5] = 0, i[6] = 0, etc. but rather i[my_tab_id], which doesn't help more than a simple var.
Any advice? Thanks!
In that case you shouldn't use an array, you should use an object, which you can treat like a hash.
var o = {};
var id = 'x';
o[id] = 1;
alert(o[id]);
This should allow you to store the click count onto each tab using the .data() function in jQuery each time a tab is clicked.
$('#example').bind('tabsselect', function(event, ui) {
var count = parseInt(ui.tab.data("clickCount"));
if (isNaN(count)) count = 0;
count++;
ui.tab.data("clickCount", count);
});
I think I understand your problem.
You are saying that the var i only has one element. This happens because the var i is newly instantiated every time you open a new tab. I'm guessing every tab is a new page or at least is a new context for var i.
If you want to keep an instance of an object (like an array) in between different pages, take a look at jStorage, it allows you to keep data locally on the browser and it makes it easier to maintain context between page loads.
If all tabs are on the same page then the solution is easier, you need to keep the array in a global variable for the page.
Are you sure my_tab_id is an integer when i[my_tab_id] = 0; is called?