i know using <button onclick="some js code here">
, writing js directly html bad practice. it's bugging me why slow compared running included javascript file (for example when run function outer file 100x faster). seems same code execution time different.
here have example:
var i, x = 0; (i = 0; < 1000000; i++) { x += math.random() * 10 }; document.getelementbyid('value').innerhtml = x; function loop() { var x = 0; (i = 0; < 1000000; i++) { x += math.floor(math.random() * 10) }; document.getelementbyid('value').innerhtml = x; }
<h1 id="value">value</h1> <button onclick="var i, x = 0; for(i=0;i<1000000;i++){x += math.floor(math.random()*10)}; document.getelementbyid('value').innerhtml = x; ">test speed</button> <button onclick="loop()">test speed 2</button>
"test speed" , "test speed 2" buttons have identical code run second button runs faster (the 1 runs outer js file).
most js engines able optimize predefined functions, why faster. when don't define functions front, becomes harder browsers optimize js execution.