简体   繁体   English

正确的方法来使用JavaScript timeOut()

[英]Correct way to use javascript timeOut()

For example if i was to format my code as followed 例如,如果我要格式化我的代码,如下所示

<script type="text/javascript">
    var timeout;
    function auto() {
        $.ajax({
                url: "functions/ajax.php",
                data: "func=auto",
                type: "GET",
                dataType: "json",
                success: function(data){
                       $.each(data.search, function (i, v) {
                               console.log('Success ' + v);
                       });
                },
                error: function (jqXHR, textStatus, errorThrown){
                       console.log('Error ' + jqXHR);
                }
        });
     }

    function start() {
    timeout = setTimeout('auto()', 2000);
    }

    function stop(){
        clearTimeout(timeout);
}
</script>

Would it matter that my var timeout is not defined by a value ? 我的var timeout不是由值定义是否重要? since the actual timeout is not even processing, it's running the function auto() once, then stops 由于实际的超时甚至都没有处理,因此它将运行一次auto()函数,然后停止

First off, don't use quotes in the setTimeout (I'm not sure but I believe that calls eval() ), just pass in the function by reference: setTimeout(auto, 2000) ; 首先,不要在setTimeout中使用引号(我不确定,但我相信会调用eval() ),只需通过引用传递函数即可: setTimeout(auto, 2000) ;

Second of all, JavaScript is a dynamically typed language, which means variables don't have a fixed type, and they can change depending on the circumstances, therefore your code is perfectly valid. 其次,JavaScript是一种动态类型化的语言,这意味着变量没有固定的类型,并且它们可以根据情况而变化,因此您的代码是完全有效的。

Lastly, if you don't plan to abort the timeout whilst it's counting, you don't need to clear it, as it will disappear after being executed. 最后,如果您不打算在计数时中止超时,则无需清除它,因为超时将在执行后消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM