如何将函数转换为setTimeout

how to transform function to setTimeout

本文关键字:setTimeout 转换 函数      更新时间:2023-09-26

我现在使用setInterval,但希望使用setTimeout。

$.when(
            data['layout'] = "getMessages",
            data['limit'] = limit,
            fetchMsg(data,'[data-messages]',{"background-color":"#fff"})
        ).then(
            setInterval(function(){ 
                data['lastupdate'] = localStorage.lastupdate;
                data['layout'] = "getNewMessages",
                fetchMsg(data, '[data-body-new]',{"background-color":"#b4eeb4"});
            }, 1000)
        );

//功能

function fetchMsg(info, container, messageStyle){
            $.ajax({
               method: "POST",
               url: window.root+"/index.php",
               "data": info,
               error: function() {
                 alert('error');
               },  
               success: function(result) {
                  ..........
                 }
              });

我试过下面的,但不起作用:

setTimeout(function(){ 
    data['lastupdate'] = localStorage.lastupdate;
    data['layout'] = "getNewMessages",
    fetchMsg(data, '[data-body-new]',{"background-color":"#b4eeb4"});                   
}, 1000)

//功能

function fetchMsg(info, container, messageStyle){
                $.ajax({
                   method: "POST",
                   url: window.root+"/index.php",
                   "data": info,
                   error: function() {
                     alert('error');
                   },  
                   success: function(result) {
                      ..........
                     },
                  complete:fetchMsg
                  });

我不会为您修复代码,但这里有一个从间隔到setTimeout的基本想法。

首先,让你的"区间"等于一个变量。

var init = setInterval(doFunc,1000);

稍后当您想要进行更改时:

clearInterval(init);

然后设置超时只需执行:

setTimeout(doFunc);

基本上就是这样。