I can use setTimeout
to make a message show up three seconds after I click a button, like this:
document.getElementsByTagName("button")[0].onclick = function() {
setTimeout(function() {
alert("You clicked the button three seconds ago.");
}, 3000);
}
<button>Click me</button>
But for some reason, when I try to make the message show up three seconds before I click the button, it doesn't seem to work.
document.getElementsByTagName("button")[0].onclick = function() {
setTimeout(function() {
alert("You will click the button three seconds from now.");
}, -3000);
}
<button>Click me</button>
I expect the message to show up -3000 milliseconds after I click the button, that is, three seconds before I click the button, but actually it shows up immediately after I click the button. It seems that setTimeout
doesn't support a negative second argument.
Is there any reason why it isn't working? Are there any workarounds or polyfills to support this missing functionality?