function debounce(quietMillis, fn, ctx) {
ctx = ctx || undefined;
var timeout;
return function () {
var args = arguments;
window.clearTimeout(timeout);
timeout = window.setTimeout(function() {
fn.apply(ctx, args);
}, quietMillis);
};
}
$('[name="cep"]').keyup(debounce(500,async (evt) => {
const zipcode = evt.target.value.replace(/\D/g, '');
console.log("findViaCep", zipcode);
const url = 'https://viacep.com.br/ws/'+zipcode+'/json'
const result = await fetch(url).then((e) => e.json());
$(`#uf`).val(result.uf);
$(`#uf`).trigger('change');
setTimeout(()=>{
console.log('timeout');
$(`#cidade option`).filter(function() {
console.log($(this).text(),result.localidade,$(this).text() == result.localidade);
return $(this).text() == result.localidade;
}).attr('selected', true);
$(`#cidade`).trigger('change');
},1000)
$(`[name='endereco']`).val(result.logradouro);
$(`[name='bairro']`).val(result.bairro);
$(`[name='numero']`).focus();
}));