Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

javascript - How to set delay inside function - a problem with setTimeout

I made a function to print innerHTML and its stylesheet of a div.

I'm having a little problem here though, because the div needs some external fontface files to load, the window.print() needs a small delay, in order to wait for the font files to load completely before it executes.

So I used setTimeout() in order to delay print() for a few seconds, but it doesn't seem to work, when the function is executed, the printing page of the browser still loads immediately. Is there any way to improve this code?

function printdiv() {
  var headstr = "<html><head><title>file_name</title></head><body>";
  var footstr = "</body></html>";
  var newstrstyle = document.getElementsByTagName("style")[0].innerHTML;
  var newstr = document.getElementById("divID").innerHTML;
  var oldstr = document.body.innerHTML;
  document.body.innerHTML =
    headstr + "<style>" + newstrstyle + "</style>" +"<div id='divID'>" + newstr + "</div>" + footstr;
  setTimeout(window.print(), 2000); // is this right?
  document.body.innerHTML = oldstr;
  return false;
}
question from:https://stackoverflow.com/questions/65873965/how-to-set-delay-inside-function-a-problem-with-settimeout

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It will be better to do it when the document content is loaded.

document.addEventListener('DOMContentLoaded', function(event) {
    window.print();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...