首页 > 解决方案 > SetimeOut 间隔因“无法将未定义或空值转换为对象”而失败

问题描述

我正在使用 Tampermonkey 编写用户脚本,但无法解决此错误,我们将不胜感激。

我很好地检测到键,空格键触发此功能,只要键保持在向下位置,该功能就会重复。控制台通常将输出写入或多或少 30 秒,然后出现 TypeError。

根据声誉限制,这是一个屏幕截图:

用户脚本:

// ==UserScript==
// @name         TEST STUFF--------------------
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @run-at         document-start
// @include        http://*
// @include        https://*
// @grant        none
// ==/UserScript==

( function()
{
    'use strict';
    window.addEventListener ( "keydown", CaptureKeyPress );
    window.addEventListener ( "keyup", CaptureKeyPress );
    var Hotkeys =
    {
        perform: 32
    };
    var HotkeyToggle = false;
    function CaptureKeyPress ( a )
    {
        if ( a.keyCode == Hotkeys.perform )
        {
            a.preventDefault();
            a.stopPropagation();
            a.cancelBubble = true;
            a.stopImmediatePropagation();

            if ( a.type == "keydown" && !HotkeyToggle )
            {
                console.clear();
                HotkeyToggle = true;
                perform();
            }

            if ( a.type == "keyup" && HotkeyToggle )
            {
                HotkeyToggle = false;
            }
        }
    }
    function perform()
    {
        if(HotkeyToggle == false) // exit
        {
            return 0
        }
        //do stuff...

        console.info("working...");
        if(HotkeyToggle == true) // continue after everything completes
        {
            setTimeout(() => {
                perform()
            }, 280);
            return 0
        }
        return 1
    }
} ) ();

标签: javascriptuserscriptstampermonkey

解决方案


这要么是 TamperMonkey 特有的问题,要么是 Chrome 本身的新安全策略/错误——我遇到了同样的事情并在调试器中捕获了它,并且没有一个参数是 null/undefined;setTimeout 未被覆盖。

编辑:有问题的用户脚本和我正在调试的用户脚本之间的一个共同特征是 setTimeout 的“递归”使用。我把它改成了一个setInterval,这似乎在我的情况下已经解决了。 在此处输入图像描述


推荐阅读