setTimeout()在js类中的使用方法

setTimeout的作用和用法 setTimeout是 JavaScript 里的一个内置函数,其作用是在指定的延迟时间之后执行一次指定的函数或者代码片段。 阅读详情


setTimeout (表达式,延时时间)
setTimeout(表达式,交互时间)

延时时间/交互时间是以豪秒为单位的(1000ms=1s)

setTimeout  在执行时,是在载入后延迟指定时间后,去执行一次表达式,仅执行一次
setTimeout 在执行时,它从载入后,每隔指定的时间就执行一次表达式

1,基本用法:
   执行一段代码:
   var i=0;
   setTimeout("i+=1;alert(i)",1000);
   执行一个函数:
   var i=0;
   setTimeout(function(){i+=1;alert(i);},1000);
  
   //注意比较上面的两种方法的不同。

   下面再来一个执行函数的:
   var i=0;
   function test(){
       i+=1;
       alert(i);
   }
   setTimeout("test()",1000);
   也可以这样:
   setTimeout(test,1000);

   总结:
   setTimeout的原型是这样的:
   iTimerID = window.setTimeout(vCode, iMilliSeconds [, sLanguage])
  
  setTimeout有两种形式

  setTimeout(code,interval)
  setTimeout(func,interval,args)

  其中code是一个字符串
  func是一个函数.

  注意"函数"的意义,是一个表达式,而不是一个语句.
  比如你想周期性执行一个函数
  function a(){
      //...
  }
  可写为
  setTimeout("a()",1000)
  或
  setTimeout(a,1000)

  这里注意第二种形式中,是a,不要写成a(),切记!!!
  展开来说,不管你这里写的是什么,如果是一个变量,一定是一个指向某函数的变量;如果是个函数,那它的返回值就  要是个函数

  2,用setTimeout实现setInterval的功能
    思路很简单,就是在一个函数中调用不停执行自己,有点像递归
    var i=0;
    function xilou(){
        i+=1;
        if(i>10){alert(i);return;}
        setTimeout("xilou()",1000);
        //用这个也可以
        //setTimeout(xilou,1000);
    }
   
    3,在类中使用setTimeout

    终于到正题了,其实在类中使用大家遇到的问题都是关于this的,只要解决了这个this的问题就万事无忧了。
呵呵。让我们来分析一下:
   
    function xilou(){

        this.name="xilou";
        this.sex="男";
        this.num=0;
    }
    xilou.prototype.count=function(){
        this.num+=1;
        alert(this.num);
        if(this.num>10){return;}
        //下面用四种方法测试,一个一个轮流测试。
        setTimeout("this.count()",1000);//A:当下面的x.count()调用时会发生错误:对象不支持此属性或方法。
        setTimeout("count()",1000);//B:错误显示:缺少对象
        setTimeout(count,1000);//C:错误显示:'count'未定义
        //下面是第四种
        var self=this;
        setTimeout(function(){self.count();},1000);//D:正确
       
    }
   
    var x=new xilou();
    x.count();
   
    错误分析:
    A:中的this其实指是window对象,并不是指当前实例对象
    B:和C:中的count()和count其实指的是单独的一个名为count()的函数,但也可以是window.count(),因为window.count()可以省略为count()
    D:将变量self指向当前实例对象,这样js解析引擎就不会混肴this指的是谁了。
   
    话说回来,虽然我们知道setTimeout("this.count()",1000)中的this指的是window对象,但还是不明白为什么会是
    window对象^_^(有点头晕...)
    那我们可以想象一下这个setTimeout是怎样被定义的:
    setTimeout是window的一个方法,全称是这样的:window.setTimeout()
    那应该是这样被定义的:
    window.setTimeout=function(vCode, iMilliSeconds [, sLanguage]){
        //.....代码
        return timer//返回一个标记符
    }
    所以当向setTimeout()传入this的时候,当然指的是它所属的当前对象window了。

 


关于setTimeout的知识点以及setTimeout(0)的使用场景 试试以下例子: <!DOCTYPE html> <html> <head> <title>demo</title> </head> <body> <input type="text" onkeydown="show()"> <script type="text/javascript"... 阅读详情

相关推荐

解决vue的变量在settimeout内部效果失效的问题

解决方法如下: 1、定义一个self暂存this 2、再改变变量的值,则生效啦 var self=this; this.toastrVal = inVal; this.loadState = true; this.noBg = bgState; setTimeout(function () { self.loadState = false; }, 3000) 拓展知识:解决vue在setTimeout内修改this失效的问题 当在vue中使用定时器来修改一个变量值的时候,发现没有效果,这是由于setTimeout函数调用的代码运行在与所

setTimeout 用法

总的来说用法就一种: setTimeout(要执行的代码,间隔时间,参数1,参数2); 但是要执行的代码有几种写法,分别如下: 如果执行的代码不需要参数,有3种写法如下: 1,直接将js代码写在字符串中: setTimeout("alert(123)",500); 2,在字符串中调用函数: setTimeout("callFun()",500); function callFun(){ alert(456); } 3,使用匿名函数: setTimeout(()=

weixin_43833851的博客 1万+

SAP EWM 内向交货流程(一)

本文介绍了SAP EWM系统中内向交货单的基本配置与操作流程。

huqinghai的专栏 2398

JavaScript中setTimeout()的用法详解

要使用 clearTimeout( ), 我们设定 setTimeout( ) 时, 要给予这 setTimout( ) 一个名称, 这名称就是 timeoutID , 我们叫停时, 就是用这 timeoutID来叫停, 这是一个自定义名称,。这处的 flag 是一个变数, 可任意取名, 我们用 flag来称呼这变数的原因, 是因为这变数好处一支旗, 将旗竖起 (flag is on), 就会产生一个作用, 将旗放下 (flag is off), 就产生另一个作用。

suwu150 12万+

数字IC物理验证实战 | 从Calibre LVS报告到Innovus定位的Debug全链路解析

本文详细解析了数字IC物理验证中Calibre LVS报告的Debug全流程,从INCORRECT NETS错误的初探到Innovus定位技巧,提供了实战案例和高效工具的使用方法。重点介绍了Calibre高亮功能、Innovus验证命令以及前后端工具联动的关键策略,帮助工程师快速定位和解决LVS问题,提升物理验证效率。

weixin_30919429的博客 127

CTF-Web学习笔记:服务端请求伪造(SSRF)篇

本文系统介绍了CTF比赛中SSRF漏洞的攻防技术。首先解析了SSRF的核心原理,即利用服务器对用户输入URL的未校验缺陷,诱导其访问内网资源。然后详细分析了5类常见CTF题型:文件读取、内网探测、云服务元数据窃取、协议绕过及组合漏洞利用。重点讲解了绕过URL过滤、利用特殊协议(如dict://、gopher://)等实战技巧,并通过一道SSRF+Redis的高阶题目演示完整攻击链。最后给出防御建议:严格校验输入URL、禁用危险协议、实施内网隔离等。

Deng7326的博客 1702

在js类中 setTimeout() 和 setInterval() 的使用方法详解

setTimeout(表达式,延迟时间); 单位:ms(毫秒);1s=1000ms;    setInterval(表达式,交互时间);  单位:ms(毫秒);1s=1000ms;    window.setTimeout()    在执行时,它从载入后延迟指定的时间去执行一个表达式或者是函数;仅执行一次;和window.clearTimeout一起使用.   window.se...

訫誶 233

Linux内核同步原语之队列自旋锁(Queued Spin Lock)深度解析

本文深度解析了Linux内核中的队列自旋锁(Queued Spin Lock)机制。通过对比传统自旋锁的瓶颈,详细阐述了队列自旋锁如何利用紧凑的4字节结构、每CPU节点数组和pending位优化,有效解决多核(SMP)系统中的缓存行乒乓和惊群效应,实现公平、高效的锁等待队列,从而显著提升内核在高并发场景下的可扩展性与性能。

weixin_29205061的博客 303

js setTimeout 在类中,绑定this的方法

setTimeout 最常用的用法是: setTimeout(functionName,1000); //functionName 为一个函数的名字 在一个类中,调用setTimeout,会出现问题,this指向了window var firstName = "zhengxiang"; var name ={ firstName : "xiong", showNa

xiongzhengxiang的专栏 7091

Ubuntu 24.04 + RTX 5090 部署 OpenVLA-OFT:从环境配置到机器人任务评估实战

本文详细记录了在Ubuntu 24.04 LTS系统上,为全新RTX 5090显卡配置CUDA 12.8+与PyTorch 2.7.1+开发环境,并成功部署OpenVLA-OFT视觉语言模型进行机器人任务评估的完整实战流程。文章重点解决了驱动安装、依赖版本冲突、路径设置等核心难题,为在最新硬件上运行先进AI机器人模型提供了可靠的避坑指南和性能观察。

n8m7b6v5c4的博客 595

从 SAP HANA 到 ABAP Cloud:彻底讲透 scalar function 的定位、实现方式与 Clean Core 实践

SAP项目中,scalar function是数据库层的重要计算单元,用于封装可复用的单值逻辑。不同于返回结果集的table function,它直接嵌入SQL表达式,适用于折扣率计算、数据标准化等场景。在SAP技术栈中,scalar function有三种形态:原生SQLScript函数、AMDP托管函数和CDS绑定函数。正确使用可提升查询性能,但需注意与procedure、table function的边界区分。AMDP scalar function是ABAP项目中的推荐实现方式,能确保函数生命周期受

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1668

构建 JS 中的异步任务队列和发布-订阅架构

在 JS 中构建异步任务队列和发布-订阅架构可以有效利用 JavaScript 的并发模型和性能。 ### 1. 异步任务队列: 对于异步任务队列,你可以使用 async 库,但我们可以使用原生 JavaScript 的 Promise 和 setTimeout 来构建一个简单的任务队列。

hongfu951的专栏 1518

cannot import name ‘BUFSIZE‘ from ‘numpy‘ 解决方案

本文主要介绍了cannot import name ‘BUFSIZE’ from ‘numpy’ 解决方案,希望能对使用numpy的同学们有所帮助。 文章目录 1. 问题描述 2. 解决方案

weixin_43178406的博客 22万+

java中timer类包,Java中的Timer类

有人说,Java和Javascript的关系,就像雷锋和雷峰塔的关系!换句话说,就是毛关系没有!我从Java到Javascript,三年后,又从Javascript回到了Java!不扯淡了,对比着Javascript来记录个小东西:Javascript中有setTimeout和setInterval,很是方便;Java也很体贴,有Timer类。// 创建Timer实例Timer timer = n...

weixin_39903571的博客 329

Qt5.15.7编译报错问题汇总:python2安装环境导致的问题

导致编译生成的:RegExpJitTables.h文件大小为0。RegExpJitTables.h 能生成且大小不为0KB。可以看到,正确的python路径,执行编译路径后。再执行 configure XXX…尝试直接改,将其改为正确的路径。

MusicScore的博客 1439

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

JS settimeout 解析

转载:http://www.cnblogs.com/zhangzheny/archive/2007/12/03/981200.html setTimeout()在js类中的使用方法    setTimeout (表达式,延时时间) setTimeout(表达式,交互时间) 延时时间/交互时间是以豪秒为单位的(1000ms=1s) setTimeout  在执行时,是在载入后延

lianliange85的专栏 697

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

(原创)飘浮广告显示脚本类(VBS,JS双版)

在写一个项目时要用到广告模块,为了不想用ASP生成脚本代码时较麻烦,于是产生了写脚本类的念头,即是用一个类模块的脚本代码去控制所有在同一页面显示的漂浮广告。但在写的过程中发现JS脚本竟然在setTimeout里不能使用类的方法。奇怪,是不是我弄错了还是JS脚本就不能这样??但VBS脚本就可以!我晕……不说了,贴代码:[VBS脚本代码]/****************漂浮广告显示类*****

鱼的天堂与地狱 1870

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

js中的setTimeout详解

setTimeout的原型是这样的:   iTimerID = window.setTimeout(vCode, iMilliSeconds [, sLanguage])     setTimeout有两种形式  setTimeout(code,interval)  setTimeout(func,interval,args)  其中code是一个字符串  func是一个函数.  注意

hjjk123的专栏 672

● JS中的window.setTimeout()详解

setTimeout (表达式,延时时间)setInterval (表达式,交互时间)其中延时时间/交互时间是以豪秒为单位的(1000ms=1s) setTimeout 在执行时,是在载入后延迟指定时间后,去执行一次表达式,仅执行一次setInterval 在执行时,它从载入后,每隔指定的时间就执行一次表达式 1,基本用法:    var i=0;setTimeout("i+=1;ale...

shuixian 376

JavaScript window.setTimeout() 的详细用法

setTimeout (表达式,延时时间) setTimeout(表达式,交互时间) 延时时间/交互时间是以豪秒为单位的(1000ms=1s) setTimeout 在执行时,是在载入后延迟指定时间后,去执行一次表达式,仅执行一次 setTimeout 在执行时,它从载入后,每隔指定的时间就执行一次表达式 1,基本用法: 执行一段代码: 复制代码 代码如下: var i=0;...

阿O、不拽 198
上一篇: JS中setTimeout()的用法详解
下一篇: Html 的tbody
普通网友
博客等级 码龄15年 4粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值