简体   繁体   中英

setTimout() ajax request doesn't work successfully

In the code below the line

setTimeout(Comet_IrsaliyeBelgeDurum(sGuid, belgeOid), 10000)

doesn't make the Comet Function wait 10 seconds. The Function is running continuously.

The setTimeout parameter seems to have no effect.

How do I make the code wait 10 seconds?

function Comet_IrsaliyeBelgeDurum(sGuid, belgeOid) {

            var params = {
                sGuid: sGuid,
                belgeOid: belgeOid
            }

            $.ajax({
                type: "post",
                dataType: "json",
                data: params,
                url: '/BetonHareketler/H_BetonIrsaliyeBelgeDurum',
                success: function (data) {

                    if (data.isSuccess) {

                        if (data.entity == 2 || data.entity == 4) {
                            toastr.success(data.SuccessfullMessage, 'İşlemi Başarılı');
                        }
                        else {
                            toastr.info(data.SuccessfullMessage, 'İşlemi Başarılı');
                            setTimeout(Comet_IrsaliyeBelgeDurum(sGuid, belgeOid), 10000);
                        }

                    }
                    else {
                        toastr.error(data.SuccessfullMessage, 'İşlemi Başarısız');
                    }

                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("Bağlantı Hatası. Sayfaya Yenileyin");
                    window.location.replace(window.location.href);
                }
            });

        }

setTimeout accepts a function which it calls after the delay has passed.

setTimeout(Comet_IrsaliyeBelgeDurum(sGuid, belgeOid), 10000);
           ^---------------------------------------^
                      this got evaluated

What your code is doing is call Comet_IrsaliyeBelgeDurum and used its return value, whatever it is, as the "function" for setTimeout .

What you need to do is just wrap this in another function like so:

setTimeout(function(){
  Comet_IrsaliyeBelgeDurum(sGuid, belgeOid)
}, 10000);

The problem is the way you call setTimeout:

setTimeout(Comet_IrsaliyeBelgeDurum(sGuid, belgeOid), 10000);

Javascript is a pass-by-value language. This means that all the paramaters you pass are evaluated before they are given to the function.

This means that you are passing the values, Comet_IrsaliyeBelgeDurum(sGuid, belgeOid) and 10000 to setTimeout. This then calls the function Comet_IrsaliyeBelgeDurum .

What you want to do is pass a function (not the result of a function) to setTimeout . See Joseph's answer for an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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