Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get JavaScript to delay, and then refresh the page

I'd like my JavaScript to, at the end of the function I have created, wait seven seconds, and then refresh my page. If it is important, I have the vital parts of my JavaScript and HTML below...


Javascript:

var textfill = function () {
    var node = document.createElement("P");
    var x = document.getElementById('entertext').value;
    var textnode = document.createTextNode("The search results for: '" + x + "' will show up here");
    node.appendChild(textnode);
    document.getElementById("123").appendChild(node);
}

HTML:

 <input type="text" id="entertext">
 <input type="button" onclick="textfill()" value="Search">
 <p id="123">
 </p>
like image 587
AHolasek Avatar asked Oct 27 '25 23:10

AHolasek


2 Answers

function refreshPage() {
    //ensure reloading from server instead of cache
    location.reload(true);
}
function delayRefreshPage(mileSeconds) {
    window.setTimeout(refreshPage, mileSeconds);
}
var textfill = function () {
    var node = document.createElement("P");
    var x = document.getElementById('entertext').value;
    var textnode = document.createTextNode("The search results for: '" + x + "' will show up here");
    node.appendChild(textnode);
    document.getElementById("123").appendChild(node);
    delayRefreshPage(2000);
}

Summarizing @ioseph and my personal experience.

like image 168
Jeff Chung Avatar answered Oct 29 '25 13:10

Jeff Chung


To do something after a certain amount of time use setTimeout - https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

And to refresh the page, call

window.location.reload
like image 38
ioseph Avatar answered Oct 29 '25 14:10

ioseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!