如何暂停 addEventListener 半秒?
how to suspend addEventListener for half a second?
我有这段代码(工作正常):
chiffreId.addEventListener('input', function () {
fetch(url).then((response) =>
response.json().then(data => {
this.value = String(data.montant).replace(/\./, ','), //replace . with , for EU
soldeId.innerHTML = data.solde;
})
);
});
如何暂停执行 fetch
代码半秒?
仅在超时时调用fetch
,并在每次事件触发时清除超时并开始一个新的。
您还可以通过返回 .json
Promise 来避免一层 .then
嵌套:
let timeoutId;
chiffreId.addEventListener('input', function () {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fetch(url)
.then(response => response.json())
.then(data => {
this.value = String(data.montant).replace(/\./, ','); //replace . with , for EU
soldeId.innerHTML = data.solde
});
}, 500);
})
您可以使用setTimeout
方法在给定时间后执行函数。参数time
应该以毫秒为单位。
试试这个:-
chiffreId.addEventListener('input' , function () {
setTimeout(function () {
fetch(url).then((response) =>
response.json().then(data => {
this.value = String(data.montant).replace(/\./,','), //replace . with , for EU
soldeId.innerHTML = data.solde
})
)
}, 500)
})
我有这段代码(工作正常):
chiffreId.addEventListener('input', function () {
fetch(url).then((response) =>
response.json().then(data => {
this.value = String(data.montant).replace(/\./, ','), //replace . with , for EU
soldeId.innerHTML = data.solde;
})
);
});
如何暂停执行 fetch
代码半秒?
仅在超时时调用fetch
,并在每次事件触发时清除超时并开始一个新的。
您还可以通过返回 .json
Promise 来避免一层 .then
嵌套:
let timeoutId;
chiffreId.addEventListener('input', function () {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fetch(url)
.then(response => response.json())
.then(data => {
this.value = String(data.montant).replace(/\./, ','); //replace . with , for EU
soldeId.innerHTML = data.solde
});
}, 500);
})
您可以使用setTimeout
方法在给定时间后执行函数。参数time
应该以毫秒为单位。
试试这个:-
chiffreId.addEventListener('input' , function () {
setTimeout(function () {
fetch(url).then((response) =>
response.json().then(data => {
this.value = String(data.montant).replace(/\./,','), //replace . with , for EU
soldeId.innerHTML = data.solde
})
)
}, 500)
})