Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I optimize this recursive function which calls setTimeout()

The following function is using 100% of a CPU core on my computer. Is there a way I could rewrite it to be non-recursive? Would that fix it or is it because my CPU sucks? Are others seeing the same performance problems on their computer?

Code:

<html>
<head>
    <script type="text/javascript" src="jquery-1.7.1.js"></script>
    <script type="text/javascript">
        function timeMsg(n,max,delay)
        {
            writeToLog(n + "th: &#" + n,n);
            var temp = n + 1;
            if(n < max){
                var t=setTimeout("timeMsg(" + temp + "," + max + "," + delay + ")",delay);
            }

        }
        function writeToLog(text,n){
            $("#log").html($("#log").html() + text + "<br/>");
            //autoscrolling: doesn't work...'

        }
    </script>
</head>

<body>
    <form>
        <input type="button" value="Display alert box in 3 seconds" onClick="timeMsg(0,100000,100)" />
    </form>

    <div id="log"></div>

</body>

like image 742
user269334 Avatar asked Jun 07 '26 04:06

user269334


1 Answers

Instead of repeatedly calling setTimeout with slightly-different values, you could setup a global variable to track the current iteration, and use one call to setInterval() instead. setInterval is like setTimeout, except it will keep running indefinitely - you don't have to call it over and over again. That might help, a bit.

like image 133
Jake Feasel Avatar answered Jun 10 '26 17:06

Jake Feasel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!