-->

setInterval performance [duplicate]

2019-09-19 00:38发布

问题:

Possible Duplicate:
Javascript: setInterval() behaviour with 0 milliseconds

I simply want to hear, if it is a problem having a setInterval with time set to 0 milliseconds? Will there be any performance issues? And will it be better to have e.g. 1000 milliseconds?

I have this script:

var countdown_id = setInterval(function() {
    var now = (new Date()).getTime()-(2*60*60*1000);
    ;
    $('.product').each(function() {
        var elm = $(this).attr('id');
        var prod_id = $("#"+elm+" #hidden-"+elm).val();


        var expires = $('#date-end-' + prod_id).val()*1000;

        var seconds_remaining = Math.round((expires - now)/1000);

        var hours = FormatNumberLength(Math.floor(seconds_remaining/(60*60)), 2);
        var sec_remaining = seconds_remaining-(hours*60*60);
        var minutes = FormatNumberLength(Math.floor(sec_remaining/60), 2);
        var sec_remaining2 = sec_remaining-(minutes*60);
        var seconds = FormatNumberLength(sec_remaining2, 2);

        var timestr = hours + ":" + minutes + ":"+seconds;

        if (expires) {
            if (seconds_remaining > 0) {
                $('#'+elm+' .time_left div').text(timestr);
            }
            else {
                $(this).hide();
            }
        }
        $('#'+elm+' .time_left div').text(timestr);
    });
}, 0);

Thanks in advance!

回答1:

if it is a problem having a setInterval with time set to 0 milliseconds?

You can't set 0 as the interval, as the browser will ignore it.

Will there be any performance issues? And will it be better to have e.g. 1000 milliseconds?

Of course 1000 milliseconds is better than 10(not zero) if it's possible.
Doing a thing every 10 ms costs you more than doing that exact thing only once 1000 ms.



回答2:

Javascript is not multithreaded, it just simulates it with delayed execution. When the timer reaches your timeout interval, it will pause all other execution and run the code you told it to. Because of this, you might want to be careful about how short your interval is. It will probably tank your browser if you aren't careful.