这是一个最简单的计时器小例子,也是setInterval最标准的写法。咱们再来看看第二种写法~<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>setInterval?!</title> </head> <body> <script> setInterval(move,1000); function move(){ alert(1) } </script> </body> </html>
这样写setInterval同样能正常调用move函数,再来看看第3种写法~<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>setInterval?!</title> </head> <body> <script> setInterval("move()",1000); function move(){ alert(1) } </script> </body> </html>
这种写法能发现move只运行了一次。为什么呢?<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>setInterval?!</title> </head> <body> <script> setInterval(move(),1000); function move(){ alert(1) } </script> </body> </html>
这样就OK了~。<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>setInterval?!</title> </head> <body> <script> setInterval(move(),1000); function move(){ alert(1) return move; } </script> </body> </html>