javascript - 替换的超时事件触发两次或更多次(有时)

标签 javascript angularjs settimeout

我有一个内容部分,允许用户双击它来编辑它。如果用户更改内容后停止2秒,则更新后的内容会发送到服务器保存。

为此,我将一个 input 事件监听器绑定(bind)到启动 2 秒倒计时的部分,如果已经有倒计时,则前一个倒计时将被取消,新的倒计时将开始反而。倒计时结束时,将包含新数据的 http POST 请求发送到服务器。

问题是,有时在倒计时结束时我会看到发送了 2 个或更多请求,就好像倒计时在插入新请求之前没有取消一样,我不明白为什么。

有问题的代码如下:

//this function is bound to a double-click event on an element
function makeEditable(elem, attr) {

    //holder for the timeout promise
    var toSaveTimeout = undefined;

    elem.attr("contentEditable", "true");
    elem.on("input", function () {

        //if a countdown is already in place, cancel it
        if(toSaveTimeout) {
            //I am worried that sometimes this line is skipped from some reason
            $timeout.cancel(toSaveTimeout);
        }
        toSaveTimeout = $timeout(function () {
            //The following console line will sometimes appear twice in a row, only miliseconds apart
            console.log("Sending a save. Time: " + Date.now());
            $http({
                url: "/",
                method: "POST",
                data: {
                    action: "edit_content",
                    section: attr.afeContentBox,
                    content: elem.html()
                }
            }).then(function (res) {
                $rootScope.data = "Saved";
            }, function (res) {
                $rootScope.data = "Error while saving";
            });
        }, 2000);
    });

    //The following functions will stop the above behaviour if the user clicks anywhere else on the page
    angular.element(document).on("click", function () {
        unmakeEditable(elem);
        angular.element(document).off("click");
        elem.off("click");
    });
    elem.on("click", function (e) {
        e.stopPropagation();
    });
}

最佳答案

事实证明(在上面评论者的帮助下)函数 makeEditable 被调用了不止一次。

在函数开头添加以下两行代码修复了问题:

//if element is already editable - ignore
if(elem.attr("contentEditable") === "true")
    return;

关于javascript - 替换的超时事件触发两次或更多次(有时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37029619/

相关文章:

javascript - 函数内javascript中的setTimeout

javascript - 具有相同时间的嵌套 settimeout 随机打印

javascript - 我的 chrome 扩展没有向控制台显示错误,但它显示日志

javascript - 如何告诉 MathJax 对下标使用替代语法?

javascript - 操作包含文件路径的字符串以仅获取文件名

javascript - 如何正确设置工厂

javascript - ngTable 内的常规表

javascript - 如何在超过超时时阻止 NodeJS 脚本崩溃

javascript - 很难调试错误 - 第 2 列的 token '{' 无效 key

javascript - 使用 ng-if 从 angularjs 中的另一个指令检查 Angular 变量