How to disable skipping in JavaScript console.log() [duplicate] - javascript

This question already has answers here:
How do I disable firefox console from grouping duplicate output?
(5 answers)
Closed 5 years ago.
I'm trying to measure time taken by a function to execute in JS.
When I try to console.log() the elapsed time, some blue numbers appear in the console and some of the logs are gone.
When I counted the appeared number, it matched with the number of lines of skipped log.
I'm sure you can notice the problem at the right part of screenshot.
I would like the console to show all of the logs.
Is there anything I can do? BTW, the browser is Firefox 58.0b8. (Developer Edition)

Not sure, if this will serve your purpose but this is a workaround not a solution provided by any browser.
You can add a wrapper function for console.log like below
function logToConsole(number) {
var randomNumber = Math.floor(Math.random() * 6) + 1;
console.log(number.toString() + Array(randomNumber).join(" "));
}
Here, each time console.log is called, it is padded with a random number between 1 and 6. (You can also increase the range, if you feel that there is a chance for error)
Complete example below.
function logToConsole(number) {
var randomNumber = Math.floor(Math.random() * 6) + 1;
console.log(number.toString() + Array(randomNumber).join(" "));
}
logToConsole(0.1111);
logToConsole(0.1111);
logToConsole(0.1111);
logToConsole(0.1111);
logToConsole(0.1111);

Rather than do console.log, why don't you write the time to an array a print that at the end of the test?

There are benchmarking methods in console that have very high accuracy. You can use console.time(key) and console.timeEnd(key).
https://developer.mozilla.org/en-US/docs/Web/API/Console/time
// kick off
console.time('asdf')
// later
console.timeEnd('asdf')
// VM18707:1 asdf: 2077.59716796875ms
Even calling timeEnd immediately will yield different results, so it's not likely to have multiple consecutive equal results with a more complex script.

Related

Why does my code freeze when using for loop but not specified number loop? [duplicate]

This question already has answers here:
How to make for loops in Java increase by increments other than 1
(13 answers)
Closed 8 months ago.
I figured it out but it sure took me 4 hours. It never caused any errors so I used the debug feature which wasn't much help. Since there was no error I'm unsure what else to look up before I ask my question.
for (var i = 0; i < 300; i+7) { //30:00
var random_x = getRandomInt(0, width-1);
var random_y = getRandomInt(0, height-1);
var sample_color = img.colorAt(random_x, random_y);
Solution: change i+7to i++
I'm still confused on why i+7 works when number of loops are specified but not when ran with infinity loop.
The problem with your code is that you aren't assigning the value to i again.
When you write i++ you basically write a shorthand version of i = i + 1. In your code you write i + 7 which doesn't do anything and basically is an infinite loop. You should have written i = i + 7 to assign a new value to i (or i += 7 for the shorthand version).
either use i=i+7 or i+=7
i=i+7 means you are changing the value of i by adding 7 to it. So after every increment value of i increment by 7.
For better knowledge, refer assignment operators.

Can anyone confirm this iOS 10 beta 3 Safari bug?

Our JavaScript application fails in very strange ways when running on iOS 10 beta 2 and beta 3 (running on iPhone 6). When looking at logs I can see that arrays contain NaN's and 0x00's in unexpected places. I managed to produce a test program that can quite reliably reproduce the behavior.
I have filled a bug report with Apple but haven't heard back so I am a bit concerned whether this will be fixed or not. So as a first thing, I would like to hear if someone can reproduce it and at least confirm there is a bug (and not just a misunderstanding on my part etc.). I'm fairly sure of this myself, but always good to be on the safe side! Could also be others have encountered it and found a workaround or maybe if some WebKit developers run into it, they might be able to help.
Test program showing bug
Here's the test progarm. The problem doesn't occur every time but the JavaScript code in the page can detect when it occurred and will keep refreshing the page until it occurs. On a non-affected browser, this means the page will keep refreshing. On an affected browser (such as Safari on iOS 10 beta 2 and beta 3 running on an iPhone 6) the refreshing will stop after some iterations (typically 5-10) and the display error.
The program operates by creating an uint8array of size 8192 (it seems smaller array sizes causes the error to be more rare). It will fill this array with dummy values, then call "toStr" which first allocates a new plain Array, then copies the contents of the uint8array to the plain array, narrowing each element along the way. While doing this it builds up a string containing the original value and the copied value. When the error occurs, the element in the target array turns out to be NaN which should not be able to occur since it by construction contains only integers. The doTest() function tests for whether such a NaN value is contained in the resulting string which shows that the error has occurred.
Note that within each refresh, the program runs 20 iterations and here it is also random which iteration that fails. However, I have observed that if the error doesn't occur among the first 20 of iterations, it is not likely to occur at all within this page load even if one ran an indefinite number of iterations, and this is the reason why I added the reload page logic.
Note that the program logic itself is completely deterministic so every run should be the same, which is also the case on other browsers. More detail can be seen by removing the comments from the log() statement in the doTest() function so it prints out the array.
Note that the problem seems to go away if the function "narrow" is inlined rather than being a separate function (even though these two programs should of course be semantically equivalent). Also, if one omits the shift from "state >> 8" the error also seemingly goes away so either the exact array values are significant or this rewrite somehow affects how the JIT operates. Hence, it is critical the exact program structure is used when testing for the problem.
<html>
<head>
<title>Array test page</title>
<script>
log = function(s) {
var ta = document.getElementById("ta");
ta.value += s + "\n";
}
function narrow(x_0) {
return x_0 << 24 >> 24;
}
function toStr(i8bytes) {
var bytes, i, str;
bytes = new Array(i8bytes.length);
str = '';
for (i = 0; i < 16; i++) {
bytes[i] = narrow(i8bytes[i]);
str += '*** (' + i8bytes[i] + ' - ' + bytes[i] + ')';
}
return str;
}
function doTest() {
var sz = 8192;
state = 0;
var i;
var fnd = false;
for (i = 0; i < 20; i++) {
var arr = new ArrayBuffer(sz);
var i8bytes = new Uint8Array(arr, 0, sz);
for (j = 0; j < i8bytes.length; j++) {
state = state + 1;
var v = state >> 8;
i8bytes[j] = narrow(v);
}
var str = toStr(i8bytes);
// log(str); <-- REMOVE COMMENT to show results
if (str.indexOf("NaN") !== -1) {
log("Found NaN at iteration" + i);
log(str);
fnd = true;
break;
}
}
return fnd;
}
function start() {
log("Starting: " + new Date());
if (!doTest()) {
location.reload(true); // <--- REMOVE THIS LINE TO PREVENT RELOAD
}
};
</script>
</head>
<body onload="start()">
<h1>Array test page</h1>
<p>Note that on a non-affected browser this page will reload indefinitely. On an affected browser, it
will stop reloading once the problem is detected.
<p>
<textarea id="ta" rows="10" cols="40"></textarea>
</body>
</html>

Getting wrong output when trying to loop through the first 50 even Fibonacci numbers in JavaScript [duplicate]

This question already has answers here:
Javascript looping through Fibonacci numbers and testing for even numbers
(2 answers)
Closed 8 years ago.
I am new to JavaScript and am having trouble getting my code to work. Any help/guidance is greatly appreciated.
I am getting the wrong output (currently “9.715575428267785e+30“) when trying to “displays the sum of first 50 even Fibonacci numbers”
I needed to:
1. create a loop that generates Fibonacci numbers.
2. test each one for whether it's even or odd.
3. Add up up the even ones, counting them as you go.
------------HERE IS MY CODE THUS FAR --------
<div id="sumFib" class="hwbutton">Get the Sum!</div>
The sum of the first 50 even Fibonacci numbers is:
<span class="" id="sumFibResult"></span>
<script>
var getFibSum = document.getElementById("sumFib");
getFibSum.onclick = function () {
fiftyEvenFibonacciSum();
}
function fiftyEvenFibonacciSum() {
var loopFib;
//Initialize fibonacci array
var fibonacci = new Array();
//Add fibonacci array items
fibonacci[0] = 0;
fibonacci[1] = 1;
var sum = 0;
//Since it takes 150 fib numbers to obtain 50 even, loop through that many.
for (loopFib = 2; loopFib <= 150; loopFib++) {
// Next fibonacci number = previous + one before previous
fibonacci[loopFib] = fibonacci[loopFib - 2] + fibonacci[loopFib - 1];
//test for even numbers with if then statement
var integer = parseInt(fibonacci[loopFib]);
if (integer % 2 == 0) {
//Add up the even fib numbers if even and output into dispay variable
var display = sum += fibonacci[loopFib];
//output results to html page
document.getElementById("sumFibResult").innerHTML = display;
}
}
}
</script>
http://jsfiddle.net/isherwood/38gPs
I disagree with the people saying this is a duplicate because I think the real question you are asking is "how do I debug my failing program?" I am sure that must be a duplicate too but, well, hem...
Anyhow I think what would help you a lot here is console.log(). I don't know what browser you are using but all major ones have a JS console. (I recommend Firefox with Firebug.) Add lines like:
console.log('integer for ' + loopFib + '=' + integer);
Or
console.log('display=' + display);
To the relevant points in your script. Then open your browser's JavaScript console to view the results. I already see some major boners in your code but I'm not going to correct them for you - this is your homework assignment after all and I'd rather teach a man to fish. Comment on this reply if you have any more questions.

Unresponsive Javascript checking lots of elements [duplicate]

This question already has answers here:
Running a long operation in javascript?
(5 answers)
Closed 9 years ago.
I created a brute-force like script which basically needs to check more than 27,000 options, and after each check displays the result inside a div.
The script is coded correctly and if I lower the number of options it works sufficiently well, but if I have many options, after a few seconds, a window pops up telling me that my script is unresponsive. How can I make it responsive while checking this many options.
Oh and I almost forgot, it displays data (which is displayed after every check) only when that pop-up window appears (kinda weird).
Asynchronous batch processing may solve your problem:
var options = ...; // your code
// I assume you are using something like this
function processAll() {
for(var i=0; i<options.length; ++i) ... // causes unresponsivity
}
// try to use this instead
function batchProcessing(from) {
if(from >= options.length) return;
var to = Math.min(1000, options.length-from);
for(var i=from; i<from+to; ++i) ... // your code
// run the next batch asynchronously, let the browser catch the breath
setTimeout(batchProcessing.bind(null, from+1000));
}

Displaying wrong answers

I have created a spelling game where the user spells the word by clicking on letters. To show the user how many they have wrong and right I count the amount of times the right and wrong message is displayed and print it to the user.
This works perfectly for correct answers but not for wrong answers. Can someone tell me why?
This is the script for the correct answers (works fine)...
var completeLetters = $('.wordglow2').length;
var completeWords = (completeLetters / 3);
if ($(right).show()) {
$('.counter').html("Right Answers = " + completeWords).show();
}
Here is the one for incorrect answers (exactly the same logic, but won't work!)...
var incompleteLetters = $('.wordglow4').length;
var incompleteWords = (incompleteLetters / 3);
if ($(wrong).show()) {
$('.counter2').html("Wrong Answers = " + incompleteWords).show();
}
So basically "wordglow4" is the style added to the letter when it is incorrectly spelt and "wordglow2" is the style added to the correctly spelt letters.
All the words are 3 letters long, hense the "(incompleteLetters / 3)"
Here is a fiddle to help http://jsfiddle.net/smilburn/Dxxmh/34/
the 'complete words' counter works because you always leave the '.wordglow2' style on the table cells when the word is completed. Therefor $('.wordglow2').length will always return the total completed letters (and hence words)
However, the incorrect words won't work, because as soon as the user gets it right, the style is changed (from '.wordglow4' to '.wordglow2' - p.s. you might want to think about using more descriptive class names - e.g. '.correctLetter' and '.wrongLetter'). Thus, you'll never have more than 3 '.wordglow4' letters on screen, so the incompleteWords counter will never get past 1.
To make the incorrect word counter work, you'll need to declare the counter outside the function, and do something like:
var incompleteLetters = $('.wordglow4').length;
incompleteWords += (incompleteLetters / 3);
This should then keep track of previous failures, and give you the behaviour you want
There is only ever one wrong answer indicated on the board by the table cells with the class .wordglow4, unlike the correct answers which maintain the .wordglow2 class after they have been guessed correctly.
So the count of .wordglow2 will always be correct, whereas the count of .wordglow4 will only ever be 3.
You should move the count variable outside of the .click() event and increment it when a word is guessed incorrectly.
So, in your example code, add...
var animation = false;
var incompleteWords = 0; // <-- this line
$('.drag').on('click', function(e) {
and change
var incompleteWords = (incompleteLetters / 3);
to
incompleteWords += (incompleteLetters / 3);

Categories