This article describes the method of simply testing loop running time of JS. Share it for your reference, as follows:
<!DOCTYPE html><html lang="zh-cn"><head><meta charset="UTF-8"><title>JS test loop run time</title><script> var arr = []; var max = 10000000; //Load window.addEventListener("load", function () { setTimeout(function () { //Initialize arr for (var i = 0; i < max; i++) { arr[i] = i + 1; } //Show all buttons document.getElementById("div1").style.display = "block"; document.getElementById("div2").style.display = "none"; }, 1); }); //1) Use for loop function test1() { var d1 = new Date(); var sum = 0; for (var i = 0; i < arr.length; i++) { sum += arr[i] } var d2 = new Date(); var x = d2 - d1; console.log("for calculation result: " + sum + ", time: " + x); } //2) Use for..in loop function test2() { var d1 = new Date(); var sum = 0; for (var i in arr) { sum += arr[i] } var d2 = new Date(); var x = d2 - d1; console.log("for..in calculation result: " + sum + ", time: " + x); } //3) loop function test3() { var d1 = new Date(); var sum = 0; arr.forEach(function (n) { sum += n; }) var d2 = new Date(); var x = d2 - d1; console.log("forEach calculation result: " + sum + ", time: " + x); }</script></head><body>Please press F12 to view the controller output<br /><div id="div1" style="display:none;"> <input type="button" value="using for loop" onclick="test1();" /> <br /> <input type="button" value="using for..in loop" onclick="test2();" /> <br /> <input type="button" value="using forEach loop" onclick="test3();" /> <br /> <br /></div><div id="div2"> Initializing...</div></body></html>Reproduction image:
For more information about JavaScript related content, please check out the topics of this site: "Summary of JavaScript Traversal Algorithm and Skills", "Summary of JavaScript Switching Special Effects and Skills", "Summary of JavaScript Search Algorithm Skills", "Summary of JavaScript Animation Special Effects and Skills", "Summary of JavaScript Errors and Debugging Skills", "Summary of JavaScript Data Structures and Algorithm Skills" and "Summary of JavaScript Mathematical Operation Usage"
I hope this article will be helpful to everyone's JavaScript programming.