如何将文本最后放入 setInterval 函数中?

How to put text at last in a setInterval function?

我想在使用 setInterval 的函数中最后放一段文字,但我做不到,代码如下 -

 function checkInIntervals(howManyTimes, howOften) 
 {
     var T = window.open("", "MsgWindow","width=400,height=600"); 
     var counter = 0; 
     var interval = setInterval(function() 
     { 
        T.document.title = 'MIKE!'; counter++; 
        if (counter === howManyTimes) 
        { 
            clearInterval(interval); 
        } 
        // do something 
        T.document.write('Where are you?'); 
        T.document.write("<br/>"); 
        console.log(counter, 'iteration'); 
     }, howOften)

    T.document.write('This text needs to be placed last.');//problem 
    T.document.write("<br/>");
    T.document.close(); // problem
}
checkInIntervals(3, 1000);

这里,T.document.write('This text needs to be placed last.');先出现,由于T.document.close();消失,但我需要'This text needs to be placed last.'最后出现,另外,我需要T.document.close();作为我每次 运行 函数时都需要新的 window 而没有以前的文本。

我该怎么做?

文本 T.document.write('This text needs to be placed last.') 首先出现,因为传递给 setInterval 的函数不会立即执行。在 setTimeout 被调用后继续执行并且该函数之后的下一个命令是 T.document.write('This text needs to be placed last.')

为了使这段文字最后,你应该把它放在 clearInterval 函数之前

function checkInIntervals(howManyTimes, howOften) {
    var T = window.open("", "MsgWindow","width=400,height=600"); 
        var counter = 0; 
    var interval = setInterval(function() { 
      T.document.title = 'MIKE!'; counter++; 
      // do something 
      T.document.write('Where are you?'); 
      T.document.write("<br/>");

      if (counter === howManyTimes) { 
        T.document.write('This text needs to be placed last.'); 
        T.document.write("<br/>");
        clearInterval(interval);
        return; 
      } 

      console.log(counter, 'iteration'); }, 
    howOften)

    T.document.close(); // problem
}
checkInIntervals(3, 1000);

在检查计数器的 if 中添加您想最后做的事情。

这是一个工作示例:https://jsfiddle.net/mvhL9ct2/1/

JS:

function checkInIntervals(howManyTimes, howOften) {
  var T = window.open("", "MsgWindow", "width=400,height=600");
  var counter = 0;
  var interval = setInterval(function() {
      T.document.title = 'MIKE!';
      counter++;
      // do something 
      T.document.write('Where are you?');
      T.document.write("<br/>");

      if (counter === howManyTimes) {
        T.document.write('This text needs to be placed last.');
        T.document.write("<br/>");
        clearInterval(interval);
      }

      console.log(counter, 'iteration');
    },
    howOften)

  T.document.close(); // problem
}
checkInIntervals(3, 1000);