In the book, author uses "setTimeout" to reset the form in HTML page.But I didn't find this usage in the JS document.So, why function"setTimeout()" can reset the form?
//reset
$("#reset").click(function(){
setTimeout(function() {
countChecked();//initial
$("select").change();//initial
},0);
});
function countChecked() {
var n = $("input:checked").length;
$("div").eq(0).html("<strong>"+n+" elements are selected!</strong>");
}
$("select").change(function () {
var str = "";
$("select :selected").each(function () {
str += $(this).text() + ",";
});
$("div").eq(1).html("<strong>you have selected:"+str+"</strong>");
}).trigger('change');
So, why function"setTimeout()" can reset the form?
It doesn't, it just waits to run the code within it until after the event trigged by the button click has been processed.
You haven't shown the HTML, but I'm guessing that the id="reset"
button is also type="reset"
, which does reset the form (standard HTML functionality, no scripting required). So by waiting to call countChecked
until after the reset, the code shows the state once the reset is complete.
The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
I see the time is set to 0 so it does not count.
Window setTimeout() Method: https://www.w3schools.com/jsref/met_win_settimeout.asp
setTimeout(function,0) or setTimeout(function), the zero is optional, both place the code to be executed at the end of the current code being executed, and after any updates the browser may have pending.
This was useful before ES6 to deblock the browser for scripts that took a long time to finish. Just use setTimeout for each iteration of the loop without a delay.
For example
setTimeout(function() { console.log(2) }); // will log 2 after this script finishs console.log(1)
Will place into the console log 1 then 2, not 2 then 1.
I don't see the point of doing
countChecked();//initial
$("select").change();//initial
after the code which is shown, has finished?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.