Settimeout

0

Witam,
Potrzebuje dodać do tej tej części programu funkcje settimeout. Kompletnie nie znam się na js a potrzebuje dodać tylko ten jeden fragment. Próbowałem metodami analogicznymi do tego co bym zrobił w c++, niestety nie skutecznie.

if (input.name === 'order[billing_name]') {
this.setInputValue(input, settings['order_billing_name']);
return true;
}

Bardzo dziękuję za pomoc

1
setTimeout(() => {
    if (input.name === 'order[billing_name]') {
    this.setInputValue(input, settings['order_billing_name']);
    return true;
}, 1000 /* opoznienie */ );

swoją drogą nie rozumiem, po co chcesz to timeoutować, ale może masz jakiś powód.

poza tym na tej stronie jest to też pokazane/wyjaśnione, są przykłady:
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

0

Skompilowałem program, jednak nadal nie uzyskałem tego co chciałem. Zależało mi na tym aby dane do tej rubryki były wprowadzone z odpowiednim opóźnieniem. W c++ użyłbym sleep, czytałem, że settimeout powoduje podobne działanie.

0

O ile się nie mylę to kod który wstawiłem odpowiada co coś innego niż mi się wcześniej wydawało. Poniżej wstawiam cały kod, czy mógłby ktoś tak przerobić go aby kolejne wartości były wstawiane do pól z odpowiednim opóźnieniem?

const ignoredIds = ['g-recaptcha-response', 'number_v', 'order_billing_address_3'];

export default class CheckoutService {
  static processFields(inputs, settings) {
    const successes = [];
    for (let i = 0; i < inputs.length; i += 1) {
      const success = this.processField(inputs[i], settings);
      successes.push(success);
      if (!success) {
        console.info(`Unknown field id : ${inputs[i].id}`);
      }
    }
    this.cleanup(inputs, settings);
    return successes.every(x => x === true);
  }

  static processField(input, settings) {
    const id = input.id;
    if (ignoredIds.indexOf(id) !== -1) {
      return true;
    }

    if (typeof (settings[id]) !== 'undefined') {
      this.setInputValue(input, settings[id]);
      return true;
    }
    return this.processUnknownField(input, settings);
  }

  static setInputValue(input, value, dispatchEvent=true) {
    if (value === undefined) return input;
    input.value = value;
    if (dispatchEvent) {
      input.dispatchEvent(new Event('change'));
    }
    return input;
  }

  static processUnknownField(input, settings) {
    const splittedName = settings['order_billing_name'].split(' ');
    if (input.name === 'credit_card[last_name]') {
      this.setInputValue(input, splittedName[0]);
      return true;
    }
    if (input.name === 'credit_card[first_name]') {
      this.setInputValue(input, splittedName[1]);
      return true;
    }
    if (input.name === 'order[billing_name]') {
      this.setInputValue(input, settings['order_billing_name']);
      return true;
    }

    if (input.name === 'order[email]') {
      this.setInputValue(input, settings['order_email']);
      return true;
    }

    if (input.name === 'order[tel]') {
      this.setInputValue(input, settings['order_tel']);
      return true;
    }

    if (input.name === 'order[billing_address]') {
      this.setInputValue(input, settings['bo']);
      return true;
    }

    if (input.name === 'order[billing_address_2]') {
      this.setInputValue(input, settings['oba3']);
      return true;
    }

    if (input.name === 'order[billing_city]') {
      this.setInputValue(input, settings['order_billing_city']);
      return true;
    }

    if (input.name === 'order[billing_zip]') {
      this.setInputValue(input, settings['order_billing_zip']);
      return true;
    }

    if (input.name === 'order[billing_state]') {
      this.setInputValue(input, settings['order_billing_state']);
      return true;
    }

    if (input.name === 'order[billing_country]') {
      this.setInputValue(input, settings['order_billing_country']);
      return true;
    }

    if (input.name === 'credit_card[type]') {
      this.setInputValue(input, settings['credit_card_type']);
      return true;
    }

    if (input.name === 'credit_card[month]') {
      this.setInputValue(input, settings['credit_card_month']);
      return true;
    }

    if (input.name === 'credit_card[year]') {
      this.setInputValue(input, settings['credit_card_year']);
      return true;
    }

    if (input.name === 'credit_card[nlb]' || input.name === 'credit_card[cnb]') {
      this.setInputValue(input, settings['cnb']);
      return true;
    }

    if (input.name === 'credit_card[rvv]' || input.name === 'credit_card[vval]') {
      this.setInputValue(input, settings['vval']);
      return true;
    }

    return this.processByLabel(input, settings);
  }

  static processByLabel(input, settings) {
    let parent = input.parentNode;
    let label = parent.getElementsByTagName('label')[0] || parent.querySelector('.sr-label');
    if (!label) {
      const children = parent.childNodes;
      for (let i = 0; i < children.length; i += 1) {
        const hasClass = [...children[i].classList].filter(x => x.toLowerCase().indexOf('label') !== -1).length > 0;
        if (hasClass) {
          label = children[i];
          break;
        }
      }
    }
    if (!label) return false;

    const text = label.innerText;
    if (!text) {
      return;
    }

    const inArray = function(txt, arr) {
      return arr.map(x => x.toLowerCase()).indexOf(txt.toLowerCase()) !== -1;
    };

    const hasText = arr => inArray(text, arr);

    if (hasText(['nom', 'name', 'firstname', 'lastname', 'nom', 'prenom'])) {
      this.setInputValue(input, settings['order_billing_name']);
      return true;
    }
    if (hasText(['email'])) {
      this.setInputValue(input, settings['order_email']);
      return true;
    }
    if (hasText(['tel', 'phone', 'phone number'])) {
      this.setInputValue(input, settings['order_tel']);
      return true;
    }
    if (hasText(['address', 'adresse', 'addresse'])) {
      this.setInputValue(input, settings['bo']);
      return true;
    }
    if (hasText(['address 2'])) {
      this.setInputValue(input, settings['oba3']);
      return true;
    }
    if (hasText(['city', 'ville'])) {
      this.setInputValue(input, settings['order_billing_city']);
      return true;
    }
    if (hasText(['zip', 'code postal', 'codepostal', 'code_postal', 'postal code', 'postalcode'])) {
      this.setInputValue(input, settings['order_billing_zip']);
      return true;
    }
    if (hasText(['country', 'pays'])) {
      this.setInputValue(input, settings['order_billing_country']);
      return true;
    }
    if (hasText(['state', 'état', 'etat', 'province'])) {
      this.setInputValue(input, settings['order_billing_state']);
      return true;
    }
    if (hasText(['type', 'type de carte', 'credit card type])) {
      this.setInputValue(input, settings['credit_card_type']);
      return true;
    }
    if (hasText(['numéro', 'number', 'numero'])) {
      this.setInputValue(input, settings['cnb']);
      return true;
    }
    if (hasText(['exp. date', 'exp date', 'expiry date', 'date d’exp.', 'date d\'exp.', 'date d\'expiration'])) {
      if (input.type === 'select-one') {
        const isMonth = input.options && input.options[0] && input.options[0].value[0] === '0';
        this.setInputValue(input, settings[isMonth ? 'credit_card_month' : 'credit_card_year']);
        return true;
      }
    }
    if (hasText(['CVV''])) {
      this.setInputValue(input, settings['vval']);
      return true;
    }
    return this.processByName(input, settings);
  }

  static processByName(input, settings) {
    if (Object.keys(settings).indexOf(input.name) !== -1) {
      this.setInputValue(input, settings[input.name]);
      return true;
    }
    return this.processByParent(input, settings);
  }

  static processByParent(input, settings) {
    const parent = input.parentNode;
    if (!parent) {
      return false;
    }
    const classList = [...parent.classList];
    if (classList.indexOf('credit_card_verification_value') !== -1) {
      this.setInputValue(input, settings['vval']);
      return true;
    }

    if (classList.indexOf('credit_card_number') !== -1) {
      this.setInputValue(input, settings['cnb']);
      return true;
    }

    // probably a card detail input
    if(parent.parentNode && parent.parentNode.id === 'card_details') {
      // either month/year of expiry date
      if (input.type === 'select-one') {
        const isMonth = input.options && input.options[0] && input.options[0].value[0] === '0';
        this.setInputValue(input, settings[isMonth ? 'credit_card_month' : 'credit_card_year']);
        return true;
      }

      // probably cvv
      if (input.attributes['maxlength']) {
        this.setInputValue(input, settings['vval']);
        return true;
      }

      // otherwise its probably cc number
      this.setInputValue(input, settings['cnb']);
    }
  }

  static cleanup(inputs, settings) {
    const input = document.getElementById('order_billing_state') || document.querySelector('[name="order[billing_state]"]');
    if (input) {
      this.setInputValue(input, settings['order_billing_state'], false);
      return true;
    }
    const stateLabel = document.querySelector('#state_label');
    if (stateLabel && stateLabel.parentNode) {
      const stateSelect = stateLabel.parentNode.querySelector('select');
      if (stateLabel) {
        this.setInputValue(stateSelect, settings['order_billing_state'], false);
        return true;
      }
    }

    const stateInputParent = document.querySelector('.order_billing_state');
    if (stateInputParent) {
      const selector = stateInputParent.querySelector('select');
      if (selector) {
        this.setInputValue(selector, settings['order_billing_state'], false);
        return true;
      }
    }
    return false;
  }

}

1

W JS nie ma timeout, sleep ani tym podobnych rzeczy, ponieważ jest to niechciane zachowanie w przeglądarce (sleep spowodowałby np. zablokowanie wykonywania się innych eventów). setTimeout pobiera dwa parametry: callback (funkcję, która ma się wykonać po odpowiednim opóźnieniu) oraz opóźnienie w milisekundach.

Pętlę, która robi cokolwiek tam robi można przerobić na setInterval (wykonuje podaną funkcję w odstępach czasowych, w nieskończoność więc należy ją w odpowiednim momencie zatrzymać):

const itemsCount = inputs.length;
var currentItem = 0;  // var bo potrzebny większy zasięg
var interval = setInterval(() => {
  const success = this.processField(inputs[currentItem++], settings);
  successes.push(success);
  if (!success) {
    console.info(`Unknown field id : ${inputs[i].id}`);
  }
  if (currentItem >= itemsCount) {
    clearInterval(interval);
  }
},
1000 /* opóźnienie 1000ms*/);

1 użytkowników online, w tym zalogowanych: 0, gości: 1