Сон в JavaScript - задерживается между действиями

Вам не нужно

main_menu = str(input('\nPress enter to return to main menu'))
if main_menu == '':
    main()

Ваша функция должна просто передать выполнение main() автоматически, но если вы хотите поместить что-то туда, чтобы сделать это явным, вы можете поместить return здесь.

Вариант 1:

# Allow the user to get back to the main menu(main function)
str(input('\nPress enter to return to main menu'))
# program will automatically go back to Main()

Вариант 2:

# Allow the user to get back to the main menu(main function)
str(input('\nPress enter to return to main menu'))
return # explicitly say to end this call to your function

ОБНОВЛЕНИЕ:

Вы также не запрашиваете ввод у пользователя каждый раз, но получите его один раз, прежде чем цикл. Вот ваш код с парой изменений:

def main():
    while True:  # loop forever
        # Create the menu text
        print('==================================')
        print('Box and Go')
        print('==================================\n')
        print('C: Calculate cost to ship a package')
        print('D: Display shipping cost information')
        print('X: Exit Application\n')
        # Allow the user to select a menu option
        selection = str(input('Enter your menu selection: ').upper())
        if selection == 'C':
            CalculateCost()
        elif selection == 'D':
            DisplayInfo()
        elif selection == 'X':
            print('\nThanks for choosing Box and Go!')
            break # end our forever loop


# Declare the function that shows the shipping rates
def DisplayInfo():
    print('==================================')
    print('SHIPPING COST INFORMATION')
    print('==================================\n')
    print('All packages are flat rate shipping\n')
    print('Flat Rate Envelope\t $6.70')
    print('Small Flat Rate Box\t $7.20')
    print('Medium Flat Rate Box\t $13.65')
    print('Large Flat Rate Box\t $18.90\n')

    # Allow the user to return to the main menu
    input('Press enter to return to main menu: ')


# Declare the function that will allow the user to
# find out the total price of each shipping option with tax included
def CalculateCost():
    print('==================================')
    print('COST ESTIMATOR FOR PACKAGES')
    print('==================================\n')

    # The user will select their option here
    selection = str(input('Enter type of package to send:\n(E)nvelope, (S)mall box, (M)edium Box, (L)arge box: ').upper())

    if selection == 'E':
        subtotal = 6.70
    elif selection == 'S':
        subtotal = 7.20
    elif selection == 'M':
        subtotal = 13.65
    elif selection == 'L':
        subtotal = 18.90
    # The program will call the CalcTax function to get the tax, then add that amount
    # to the subtotal, giving them the grand total cost of shipping
    print('\nTotal Shipment Cost: , format(CalcTax(subtotal) + subtotal, '.2f'), sep='')
    # Allow the user to get back to the main menu(main function)
    input('\nPress enter to return to main menu')
    return


# Declare the function that will calculate
# tax based on the shipping selection the user made,
# then pass that amount back to the CalculateCost function
# that called it
def CalcTax(number):
    subtotal = number * 0.06
    return subtotal

# Call the main function. The program executes from here
main()
118
задан Peter Mortensen 6 October 2017 в 19:52
поделиться

1 ответ

Вы можете использовать setTimeout чтобы добиться аналогичного эффекта:

var a = 1 + 3;
var b;
setTimeout(function() {
    b = a + 4;
}, (3 * 1000));

Это на самом деле не «спящий» JavaScript - он просто выполняет функцию, переданную setTimeout через определенную продолжительность (указывается в миллисекундах). Хотя можно написать функцию ожидания для JavaScript, лучше использовать setTimeout , если это возможно, поскольку она не останавливает все в течение периода ожидания.

128
ответ дан 24 November 2019 в 01:58
поделиться