简体   繁体   中英

Why this Else condition is executed?

i'm trying to understand this script of Zabiullah, which i found in " https://www.experts-exchange.com/questions/24623403/Can-a-Sharepoint-page-be-refreshed-automatically-but-just-once.html ". His post was from 2009 and he hasn't been active since then, so im asking here.

This code should reload the page only once at the beginn and prevent it from reloading next time. The code worked perfectly, but i can't understand when the Else condition of if(arguments.length ==1) is executed, since the funktion is allways called by setReloadTime(5), meaning it would be allways true ?

var reloadTimer = null;
var sURL = window.location.href;

function setReloadTime(secs) {

    if (arguments.length == 1) {
        if (reloadTimer)
            clearTimeout(reloadTimer);
        reloadTimer = setTimeout("setReloadTime()", Math.ceil(parseFloat(secs) * 1000));
    } else {
        if (sURL.indexOf("loaded=1") == -1) {
            reloadTimer = null;
            var queryString = location.search.substring(1);
            sURL += (queryString ? "&" : "?") + 'loaded=1';
            window.location = sURL;
        } else {
            clearTimeout(reloadTimer);
        }
    }
}

setReloadTime(5);

i can't understand when the Else condition of if(arguments.length ==1) is executed, since the funktion is allways called by setReloadTime(5), meaning it would be allways true

No, the code sets a timer to run it without any arguments:

reloadTimer = setTimeout("setReloadTime()", Math.ceil(parseFloat(secs) * 1000));
// Here -----------------^^^^^^^^^^^^^^^^^

That's why it takes that branch after the first call.


That said, it makes no sense to have one function do two completely different things depending on whether it has an argument. Instead, the original author of that code should have just written two functions.

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