简体   繁体   中英

Why does this Increment not work?

I'm having some problems with this code. My problem is that with the code below, it doesn't plus the detection-ratio text with the 'incr'. It just enters the incr, but doesn't plus.


This is my code.

(function loop() {
    var rand = Math.round(Math.random() * (3000 - 500)) + 500;
    var incr=Math.floor(Math.random()*6);
    setTimeout(function() {
         document.getElementById('detection-ratio').innerText = '0 / '+ ++incr;
         loop();  
    }, rand);
}());

The 'detection-ratio' text looks like this as default:

0 / 0

Then, lets say 'incr' generates the number '3', then it should increase the last 0 with 3, so it would look like this:

0 / 3

Then, lets say it's going to generate a new 'incr', lets say '5'. Then it would look like this:

0 / 8

---> But right now, it doesn't do that. It just writes the 'incr' into the 'detection-ratio' without increasing it.

I am assuming you are trying to append text to detection-ratio if so you need to

document.getElementById('detection-ratio').innerText += '0 / '+ incr;

++ before a variable is a pre-increment operator, since you are generating random numbers i am assuming that is not actually what you want.

Hope this code would help you to get the expected output, let me know if something breaks. Also stop iteration once it reaches > 26

var incr = 0;   
    (function loop() {
            var rand = Math.round(Math.random() * (3000 - 500)) + 500;
            incr +=  Math.floor(Math.random()*6);
            setTimeout(function() {
                 console.log('0 / '+ incr);
                 loop();  
            }, rand);
    }());

Thanks for the explanation and patience.

Since you're calling the loop recursively anyway, you may want to consider a more functional approach:

(function loop(startctr) {
        var rand = Math.round(Math.random() * (3000 - 500)) + 500;
        nextctr = startctr + Math.floor(Math.random()*6);
        setTimeout(function() {
             console.log('0 / '+ nextctr);
             loop(nextctr);  
        }, rand);
}(0));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM