我需要一个简单的 debounce 函数,立即数总是为真。
没有求助于 lodash 并在有人可以解释 Javascript 中的“去抖动”功能的帮助下,我实现了它如下,
function debounce(func, wait) {
var timeout;
return function() {
if (!timeout) func.apply(this, arguments);
clearTimeout(timeout);
timeout = setTimeout(()=>{timeout = null}, wait);
};
};
Run Code Online (Sandbox Code Playgroud)
它按预期工作,直到我需要去抖动 axios 请求。假设我有一个去抖动的 axios 方法,我希望调用方法像往常一样,这意味着我的去抖动 axios 方法应该返回我相信的承诺。
//the calling method should not change
debounced_axios().then(res => {...}).catch(err => {...})
Run Code Online (Sandbox Code Playgroud)
原始 debounce 实现的本质是在等待时间范围内只运行一次func ,但是我如何在等待时间范围内只返回一个承诺?
然后我想出了以下解决方案
all_timers = {}
function debounce_axios(input, wait) {
return new Promise((resolve, reject) => {
let timer = all_timers.[input] //check if it is …Run Code Online (Sandbox Code Playgroud) 我只希望每个滚动事件获得一个事件
我尝试了这段代码,但是它多次触发wheel事件时都会产生“ wheel”。有什么帮助吗?谢谢
window.addEventListener("wheel",
(e)=> {
console.log("wheel");
e.preventDefault();
},
{passive:false}
);Run Code Online (Sandbox Code Playgroud)
用例(编辑)我想只允许在页面之间滚动-滚动时带有动画。一旦我检测到onwheel事件,我想在动画结束之前将其停止,否则,前一个onwheel将继续触发并将其视为新事件,因此转到目标页面的下一个页面
我的结论:无法取消车轮事件。为了在进行滚轮事件(来自以前的用户动作)时识别新的用户滚轮动作,我们需要计算此类事件的速度/加速度
我正在尝试使用typescript编写去抖动函数。
我在这里找到了一个例子。代码如下:
export function debounce<Params extends any[]>(
func: (...args: Params) => any,
timeout: number,
): (...args: Params) => void {
let timer: NodeJS.Timeout
return (...args: Params) => {
clearTimeout(timer)
timer = setTimeout(() => {
func(...args)
}, timeout)
}
}
Run Code Online (Sandbox Code Playgroud)
问题是:
谢谢。
场景:
我们有一个MutationObserver处理函数handler。
在中handler,我们进行了一些会handler再次触发的DOM操作。从概念上讲,我们将有一个可重入handler电话。除非MutationObserver未在线程中运行,否则它将在handler完成执行后触发。
因此,handler将触发自身,但通过异步队列,而不是线程内。JS调试器似乎知道这一点,它将在调用堆栈中(即使用Chrome)作为异步祖先出现。
为了对事件进行有效的反跳,我们需要对其进行检测;也就是说,如果handler是由于自身触发的更改而被调用的。
那该怎么办呢?
mutationObserver=new MutationObserver(handler);
mutationObserver.observe(window.document,{
attributes:true,
characterData:true,
childList:true,
subtree:true
});
var isHandling;
function handler(){
console.log('handler');
// The test below won't work, as the re-entrant call
// is placed out-of-sync, after isHandling has been reset
if(isHandling){
console.log('Re-entry!');
// Throttle/debounce and completely different handling logic
return;
}
isHandling=true;
// Trigger a MutationObserver change
setTimeout(function(){
// The below condition should not …Run Code Online (Sandbox Code Playgroud)我正在尝试在 html5 canvas 上制作一个动画,该动画应该在移动时跟随可拖动的 div,如下所示:
draggable_div.draggable({
drag: function(e, ui) {
canvasDrawSomethingNearDraggable(ui);
}
stop: function(e, ui) {
canvasDrawSomethingNearDraggable(ui);
}
});
function canvasDrawRectangleUnderDraggable {
for (i = 0; i < 10; i++) { // draw overlapping circles in fixed order
context.beginPath();
context.arc(x[i], y[i], 10, 0, 2 * Math.PI, false);
context.fillStyle = c[i];
context.fill();
context.stroke();
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我移动可拖动元素时,动画滞后(移动速度越快,间隙就越大,并且仅当可拖动停止事件触发时才会关闭):

有没有办法解决或减轻这个问题?我应该计算拖动事件之间的时间并以这种方式减少对绘图函数的调用还是有更好的解决方案?
如果我的应用程序有足够多的用户,每次击键时发送一个 ajax 请求是让服务器瘫痪的有效方法(更不用说可能使客户端应用程序感觉很慢)。关于实现带有两个选项(DB 搜索和 Web Api 搜索)的符号搜索框。当我在搜索框中输入符号(例如:AAPL - aple stock)时,fetch()每次都会通过网络发送请求。为了避免它,我尝试使用,setTimeout()但fetch()无论如何都会多次发送请求。如何延迟/开始/去抖动获取请求,直到用户停止在输入区域输入以仅发送一个fetch()请求?
HTML:
<label for="symbolTags">Symbol: </label>
<input type="text" id="symbolTags" name="symbol">
<label for="api">Select Search Api: </label>
<select id="api" name="routes_api">
<option value="search">Web Search Api</option>
<option value="dbsearch">DB Search Api</option>
</select>
Run Code Online (Sandbox Code Playgroud)
JavaScript:
const symbolTags = document.querySelector('#symbolTags')
const symbolTagsOptions = document.querySelector('#api')
const urlsObject = {
dbsearch: '/dbsearch/',
search: '/search/'
}
symbolTags.oninput = function () {
let symbolTagsOptionsValue = symbolTagsOptions.value
let arg = urlsObject[symbolTagsOptionsValue]
// Init a timeout variable to …Run Code Online (Sandbox Code Playgroud) 阅读本文后,我发现去抖动是如何工作的: 有人可以解释 Javascript 中的“去抖动”功能吗?
在这个被接受的答案中有一些东西我无法弄清楚它是如何变成这样的:
“请注意,这会覆盖 timeout 的值,并且该值在多个函数调用中持续存在!”
每次调用 debounce 方法时,都会为其创建一个新堆栈,返回的函数可以访问超时值。是的,我把它理解为封闭的本质。但是在多次调用中,我们得到包装器 debounce 将产生一个新的本地超时,那么如何清除先前调用中的超时,因为它们没有绑定到相同的超时?
非常感谢,我知道这是非常基本的 JS,但我不想忽略它,因为我知道,如果理解它,我可以更了解 JS。
我正在尝试在 jQuery 中创建一个搜索功能:
$('input').on('keyup', function(){
var searchTerm = $("input").val().toLowerCase();
$('.item').each(function(){
if ($(this).filter('[data-text *= ' + searchTerm + ']').length > 0 || searchTerm.length < 1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
});
Run Code Online (Sandbox Code Playgroud)
每次用户输入内容时,都会将其与.itemdiv 的数据属性值进行比较。如果该元素的数据属性包含搜索查询,则会显示它 - 否则隐藏。
这在 Chrome 中工作得很好,但在 Safari 中,由于某种原因,当用户打字时,它确实很滞后。
有没有办法来解决这个问题?
大约有1400个div( .item),data-text每个元素的属性只有10-20个字符左右
编辑,通过删除.show()和.hide()- 并用本机 Javascript 替换来修复
我很确定答案是不可能的,但我想知道是否可以lodash.debounce使用 Ramda 来实现,这样我就可以摆脱lodash应用程序中的依赖关系,因为它就是这样。
这是我正在使用的代码
import debounce from "lodash.debounce";
import { Dispatch, useCallback, useState } from "react";
/**
* This is a variant of set state that debounces rapid changes to a state.
* This perform a shallow state check, use {@link useDebouncedDeepState}
* for a deep comparison. Internally this uses
* [lodash debounce](https://lodash.com/docs/#debounce) to perform
* the debounce operation.
* @param initialValue initial value
* @param wait debounce wait
* @param debounceSettings debounce settings.
* @returns …Run Code Online (Sandbox Code Playgroud) 我有一个名为 delay() 的 Typescript 函数,它在异步/等待模式下调用。
play(){
(async () => {
await this.delay(90000);
this.player.play();
})();
}
delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在完成 90 秒之前“杀死/中断”setTimeout 并在再次调用“播放”函数时再次开始计数?
javascript ×10
debounce ×2
debouncing ×2
typescript ×2
axios ×1
closures ×1
es6-promise ×1
events ×1
jquery ×1
jquery-ui ×1
mousewheel ×1
node.js ×1
promise ×1
ramda.js ×1
scope ×1
settimeout ×1