在继续执行代码之前,我应该如何等待几毫秒?

时间:2020-01-04 09:45:22

标签: javascript

我想避免玩家经常调用server.UpdateUserInternalData。因此,我想在UserInternalData中保存最后一个服务器的时间戳。UpdateUserInternalData调用。

我只想更新“ PlayerData1”:如果最后一个server.UpdateUserInternalData调用在当前时间(currenttimeinmilliseconds)之前至少4000毫秒,则为newdata。但是我不知道如果最后一次更新调用不是在当前时间(currenttimeinmilliseconds)之前至少4000毫秒该怎么办。

是否可以在Function1中等待,直到(((Number(playertimestamp)+ 4000)返回成功; 在“ PlayerData1”:newdata 执行之前执行。

我该怎么做?如何在Function1中等待?

function Function1(string newdata)
{
  var issuccessful = "";
  var playertimestamp = GetTimestampInternalData();
  var currenttimeinmilliseconds = getServerTimestamp();

  if ((Number(playertimestamp) + 4000) < Number(currenttimeinmilliseconds))
  {
    server.UpdateUserInternalData({
       PlayFabId: currentPlayerId,
       Data: {
           "PlayerData1": newdata
       },
       Permission: UserDataPermission.Private
    });

    issuccessful = true;

    var timestampinmilliseconds = getServerTimestamp();      
    CreateTimestampInternalData(timestampinmilliseconds);
  }

  return issuccessful;
}

function GetTimestampInternalData()
{
  var resultdata = server.GetUserInternalData({PlayFabId: currentPlayerId, Keys: "InternalDataTimestamp"});
  var currenttimestamp = "";
  if ((resultdata.Data.hasOwnProperty("InternalDataTimestamp")) && (resultdata.Data.InternalDataTimestamp.Value != null) && (resultdata.Data.InternalDataTimestamp.Value != ""))
    currenttimestamp = resultdata.Data.InternalDataTimestamp.Value;
  else
    currenttimestamp = 0;

  return currenttimestamp;
}

function CreateTimestampInternalData(currenttime)
{
  server.UpdateUserInternalData({
       PlayFabId: currentPlayerId,
       Data: {
           "InternalDataTimestamp": currenttime.toString()
       },
       Permission: UserDataPermission.Private
    });   
}

function getServerTimestamp()
{
  var now = new Date();
  var time = now.getTime();
  return time;
}

编辑: 如果我只想在执行下一行代码之前等待几秒钟,那么本文(将睡眠引入本机JavaScript)中的sleep(毫秒)功能对我有用:https://www.sitepoint.com/delay-sleep-pause-wait/

5 个答案:

答案 0 :(得分:2)

例如,您可以使用lodash中的debounce函数。

防抖动功能将您的功能延迟到X之后 自上次反跳功能以来经过的毫秒数 被调用。

用法:

_.debounce(Function1, 4000);

仅在自上次经过4000毫秒后,此功能才能运行。

答案 1 :(得分:1)

在您的代码中使用setTimeout()将会有效

setTimeout(function(){ alert("Your function here"); }, 4000); //4000 is 4 seconds

例如:

function onLoadFunction() {
  setTimeout(function(){ 
     yourfunction();
 }, 4000);
}

答案 2 :(得分:0)

您可以在keys(obj).forEach((key) => { if (checkMemberArray(obj, key)) { // Type of obj within this block is // {a: any[], b: any[], c: any[]} console.log(obj["b"].length); // TS fails to identify the error here } }); 中使用 setTimeout()以便在4秒后执行它

例如:

Function1()

一旦您的Function1()调用setTimeout(),将在给定时间(本例中为4秒)后触发,则无需将您先前的时间戳与当前时间戳进行比较4秒钟。

答案 3 :(得分:0)

您可以实现一个debounce函数,以确保使用以下函数不会每隔4000毫秒调用一次function1

let scheduled = null;
let fist_bounce = true;
/* causes function1 to be executed only once every ms milliseconds */
function debounce(newdate, ms)
{
    if (first_bounce) { // don't wait for first call
        first_bounce = false;
        function1(newdate);
    }
    else if (!scheduled) {
        scheduled = setTimeout(() => {
            function1(newdate);
            scheduled = null;
        }, ms);
    }
}

演示:

function function1(newdate)
{
    console.log('function1 called: ' + newdate);
}

let scheduled = null;
let first_debounce = true;
/* causes function1 to be executed only once every ms milliseconds */
function debounce(newdate, ms)
{
    if (first_debounce) { // don't wait the first time
        first_debounce = false;
        function1(-1);
    }
    else if (!scheduled) {
        scheduled = setTimeout(() => {
            function1(newdate);
            scheduled = null;
        }, ms);
    }
}

/* test debounce: */

let i = 0;
let interval = setInterval(() => {
    ++i;
    debounce(i, 2000); // execute function1 once every two seconds
    if (i == 40) {
        clearInterval(interval);
    }
}, 200); // call debounce every 200ms

要使多个“防反射器”可用于多种功能,我们需要使用闭包:

function make_debouncer(fn, ms)
{
    let first_debounce = true;
    let scheduled = null;
    function debounce()
    {
        let args = Array.prototype.slice.call(arguments);
        if (first_debounce) {  // don't wait for first call
            first_debounce = false;
            fn.apply(null, args);
        }
        else if (!scheduled) {
            scheduled = this.setTimeout(function() {
                fn.apply(null, args);
                scheduled = null;
            }, ms);
        }
    }

    return debounce;
}


/* test debounce: */

function Function1(newdate) {
    console.log(newdate);
}
    
// let debounce = make_debouncer(Function1, 2000); // call once every 2 seconds
// better yet, let's redefine Function1:
Function1 = make_debouncer(Function1, 2000); // call once every 2 seconds

let i = 0;
let interval = setInterval(function() {
    ++i;
    Function1(i); // call Function1 passing i as an argument
    if (i == 40) {
        clearInterval(interval);
    }
}, 200); // call debounce every 200ms

答案 4 :(得分:0)

说谎。

即使您什么也没做,都将issuccessful返回为true

为什么要等待?您不到四秒前更新了。等待3.9秒或延迟将来的更新,这会增加额外的复杂性。

此解决方案的唯一真正问题是在退出应用程序/页面之前的“最终保存”。您将需要一种不同的方法来执行保存,而与上次保存的时间无关。

可以将“ noTimeout”选项传递给该函数,但随后人们会养成传递true的习惯。