Correct jquery $ .each () shutdown - Is this a problem with the browser?

Why doesn't Firefox work properly in Firefox and not in Chrome? If I change the return value in the .each loop to true, it will work in Chrome, not Firefox. What gives?

(When it does not work, it returns only in seconds against the correct day, hour, etc.)

function time_remaining(expire_time)
    {
        var now = new Date().getTime()/1000,
        time_left = expire_time - now,
        time_left_str = '0 seconds';

        if (time_left < 1) {
            return time_left_str;
        }

        var a = {};
            a[ 12 * 30 * 24 * 60 * 60 ] = 'year',
            a[      30 * 24 * 60 * 60 ] = 'month',
            a[           24 * 60 * 60 ] = 'day',
            a[                60 * 60 ] = 'hour',
            a[                     60 ] = 'minute',
            a[                      1 ] = 'second';


        $.each(a, function (secs, str) {
            var d = time_left / secs;
            if (d >= 1) {
                var r = Math.round(d);
                time_left_str = r + ' ' + str + ((r > 1) ? 's' : '');
                return false;
            }
        });

        return time_left_str;
    }
+5
source share
1 answer

This is not a problem $.each, var a = {};- it is an object, and $.each(a, function (secs, str) {})it turns out badly, because jQuery each function only accepts an array.

need to convert objectto array, then use the function $.each.

Added new code to the function body to create objectup toarray

// converting object to array
var temp = [];
var finalArr = [];
for (val in a) {
    temp.push(val);
}

temp = temp.sort(function (a, b) {
    return a - b
});
for (var i = 0; i < temp.length; i++) {
    finalArr.push(a[temp[i]] + "|" + temp[i]);
}

and also changed the way to access the data and index of the newly created array

 function time_remaining(expire_time) {
    var now = new Date().getTime() / 1000,
        time_left = expire_time - now,
        time_left_str = '0 seconds';

    if (time_left < 1) {
        return time_left_str;
    }

    var a = {};
    a[12 * 30 * 24 * 60 * 60] = 'year',
    a[30 * 24 * 60 * 60] = 'month',
    a[24 * 60 * 60] = 'day',
    a[60 * 60] = 'hour',
    a[60] = 'minute',
    a[1] = 'second';


    // converting object to array
    var temp = [];
    var finalArr = [];
    for (val in a) {
        temp.push(val);
    }

    temp = temp.sort(function (a, b) {
        return a - b
    });
    for (var i = 0; i < temp.length; i++) {
        finalArr.push(a[temp[i]] + "|" + temp[i]);
    }

    $.each(finalArr, function (secs, str) {
        var time = time_left / parseInt(str.split("|")[1], 10);

        if (time >= 1) {

            var randomNum = Math.round(time);
            time_left_str = randomNum + ' ' + str.split("|")[0] + ((randomNum > 1) ? 's' : '');
            return true;
        }
    });

    return time_left_str;

}
+3
source

All Articles